从父组件更新孩子的状态

从父组件更新孩子的状态

本文介绍了从父组件更新孩子的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的父组件有两个子组件:

Let's say that my parent component got two child component :

Parent
| Child1
| Child2

我从Child2获得输入,并将其传递给Parent组件(到现在为止,我知道该怎么做).但是然后我需要将该输入传递给Child1以更新其状态.

I'am getting an input from Child2 and I'am passing it to the Parent component (until now, I know how to do). But then I need to pass that input to Child1 to update it's state.

我该怎么做?

推荐答案

希望您能得到主要的想法-在Parent组件中创建一个函数,该函数将更改传递给Child1的值. ReactJS:为什么要通过组件初始状态是道具还是反模式?

Hope you can get the main idea - create a function in the Parent component that will change the value passed to the Child1. ReactJS: Why is passing the component initial state a prop an anti-pattern?

class Parent extends Component {
  constructor(props){
    super(props);
    this.state = {
      value: ""
    }
  }
  changeValue(value){
    this.setState({value});
  }
  render(){
    return (
      <div>
          <Child1 value={this.state.value}/>
          <Child2 changeValue={changeValue}/>
      </div>
    )
  }
}


class Child2 extends Component {
  constructor(props) {
    super(props);
    this.state={
      input: ""
    }
  }
  handleChange(e){
    var {value} = e.target;
    this.setState({
      input: value
    },() => this.props.changeValue(value));
  }
  render(){
    return (
      <div>
          <input value={this.state.input} onChange={this.handleChange}/>
      </div>
    )
  }
}



class Child1 extends Component {

  constructor(props) {
    super(props);
    this.state={value:''}
  }
  componentWillReceiveProps(nextProps) {
    this.setState({value: nextProps.value})
  }


  render(){
    return (
      <div>
          {this.props.value}
      </div>
    )
  }
}

这篇关于从父组件更新孩子的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:01