React Components:在状态变化之间传递兄弟姐妹之间的数据

问题描述 投票:0回答:1

我在两个子组件之间的App comp中共享一个事件

App Comp

class App extends Component {        
      constructor(props) {
      super(props);
      this.state = { A : 'good'  };
    }    

 SharedEvent () {

 var newvalue =  this.setState({A:'update'}, () => {
    console.log(this.state);
    alert(this.state.A)
});
    }
      render() {
        return (        
      <div className="App">             
      <Content child1Event = {this.SharedEvent} text = {this.state.A}    
               child2Event = {this.SharedEvent} />            
         </div>
    );
  }
}

父母比赛

render(props) {
    return (
      <div className = "App">           

      <Subcontent whatever = {this.props.child1Event} name = {this.props.text}  />

      <Subcontent2 whatever = {this.props.child2Event}   />    

       </div>
    );
  }
}

儿童比赛

  constructor(props) {
    super(props);
    this.state = {  };
  }
  render() {
    return (
      <button id = 'btn' onClick = {this.props.whatever.bind(this , 'shared')} > {this.props.name} </button>
    );
  }
}

subcontent2与subontent相同

我可以成功触发两个组件的sharedEvent,但它应该更改setstate上的按钮名称,它不是我错在哪里???

reactjs react-component
1个回答
1
投票

问题可能来自以下两个问题之一:

  • 首先,你应该用SharedEvent =()=> {...你的函数代码}替换你的SharedEvent(){}函数,这是因为范围已经改变,如果你在组件中引用它来调用它的一个函数,你应该使用箭头函数或者像你所做的那样定义它们,并将它们绑定在你的构造函数中,而不是你没有完成的。
  • 其次,onClick事件按钮,按其默认行为重新启动页面,所有内容都刷新,组件状态也是如此,这可能是因为页面刷新并且状态恢复为“好”而导致您看不到文本更改的原因',所以尝试用这个替换你的onClick函数: <button onClick={e => {e.preventDefault(); this.props.whatever();}}> {this.props.name} </button>
© www.soinside.com 2019 - 2024. All rights reserved.