我试图了解子组件如何改变其父状态,并意识到我能够成功完成此操作的唯一示例(以及我在网上看到的唯一示例)都处理了从父传递给然后链接到该孩子中的事件(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>
    )
  }
}

最佳答案

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

07-24 09:49
查看更多