【问题标题】:Can child component only change parent state if event is triggered?如果事件被触发,子组件只能更改父状态吗?
【发布时间】:2018-12-22 14:49:11
【问题描述】:

我试图了解子组件如何更改其父组件的状态,并意识到我能够成功完成此操作的唯一示例(以及我在网上看到的唯一示例)处理从孩子的父母,然后链接到孩子中的事件(onClick,onChange等)。那么,子组件是否只能在子组件使用事件调用继承的回调时才改变其父组件的状态?

这行得通:

class Child extends React.Component{
  handleClick(){
    console.log('pressed')
    this.props.message('Hi mom!')
  }
  render(){
    return (<button onClick={this.handleClick.bind(this)}>Prese Me</button>)
  }
};

class Parent extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      messageFromChild: '',
    }
    this.callBackFromParent = this.callBackFromParent.bind(this);
  }
  
  callBackFromParent(dataFromChild){
    this.setState({messageFromChild: dataFromChild})
  }
  
  render(){
    return (
      <div>
        <h2>Message from Child is:</h2>
        <h2>{this.state.messageFromChild}</h2>
        
        <Child message={this.callBackFromParent}/>
      </div>
    )
  }
}

但这会导致无限循环:

class Child extends React.Component{
  render(){
    this.props.message('Hi Mom')
    return(
      <h2>Dummy message from child</h2>
    )
  }
};

class Parent extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      messageFromChild: '',
    }
    this.callBackFromParent = this.callBackFromParent.bind(this);
  }
  
  callBackFromParent(dataFromChild){
    this.setState({messageFromChild: dataFromChild})
  }
  
  render(){
    return (
      <div>
        <h2>Message from Child is:</h2>
        <h2>{this.state.messageFromChild}</h2>
        
        <Child message={this.callBackFromParent}/>
      </div>
    )
  }
}

【问题讨论】:

  • 您不一定需要将函数用作事件处理程序,但直接在渲染时调用它会导致父组件立即setState,这将导致Child 的另一个渲染组件,然后循环继续。你可以例如在ChildcomponentDidMount 中设置超时,它会正常工作。

标签: javascript reactjs react-native jsx


【解决方案1】:

您不一定需要将函数用作事件处理程序,但直接在渲染上调用它会导致父组件立即setState,这将导致Child组件的另一个渲染,并且循环继续。你可以例如在ChildcomponentDidMount 中设置超时,它会正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多