从父组件更新子状态

Mit*_*Mit 6 javascript reactjs

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

Parent
| Child1
| Child2
Run Code Online (Sandbox Code Playgroud)

我从Child2获得了一个输入,并将它传递给Parent组件(直到现在,我知道该怎么做).但是我需要将该输入传递给Child1以更新它的状态.

我怎样才能做到这一点?

kur*_*kan 15

希望你能得到主要的想法 - 在Parent组件中创建一个函数,它将改变传递给Child1的值.ReactJS:为什么将组件初始状态传递给反模式?

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但我认为这行不通,您正在将道具传递给您的 Child1,但我想要的是更新它的状态(您的 Child1 没有任何状态值)。 (2认同)