【问题标题】:Reactjs Sibling Component not getting the updated state valueReactjs兄弟组件没有获得更新的状态值
【发布时间】:2017-07-28 09:47:28
【问题描述】:

1) 如何将此值作为道具传递给 Child1 组件 2)如果我只是将状态值传递给 Child1 组件,我不会在 Child1 中获得更新的值 -

关注了不同的文章 - 关于在兄弟姐妹之间传递道具但没有任何作用.. 家长:

export default class Parent extends Component {

   constructor(props) {
    super(props);
    this.state = {
      toggledata: '',
    };
  }

   handleToggle(value) { //getting the updated value to 'value'
    this.setState({ toggledata: value });
  }

  render() {
    return (
      <div>
        <Child1 ToggleStatus={this.state.toggledata} />
        <Child2 callbackFromParent={this.handleToggle.bind(this)} />
      </div>
    );
  }
}
Parent.propTypes = {
  params: PropTypes.object,
};

孩子2:

class Child1 extends Component {
constructor(props) {
    super(props);
    this.state = {
      text: '',
    };
  }

  handleClick(event) {
    this.setState({ text: 'green' }, () => {
      this.props.callbackFromParent(this.state.text);
    });
  }

render(){
return (
          <a onClick={() => { this.handleClick(event) }} href="">
            Click me
          </a>

    );
  }
}
export default Child1;

【问题讨论】:

  • 您应该收到该代码的错误。

标签: reactjs react-jsx


【解决方案1】:

您没有将this 绑定到您的回调。 你this.setState 不是为你的父母调用的,它是在Child2 内调用的。 handleTogglethis 的上下文来自 Child2,如果不绑定则不是 Parent。

<Child2 callbackFromParent={this.handleToggle.bind(this)} />

【讨论】:

  • 那么如何调用 this.setState 来处理 Child2 中发生的点击并将其注册到父组件中并将其传递给 Child1 - 这是我的实际问题 - 可能是我没有说对,我已使用绑定更新..
猜你喜欢
  • 2019-09-17
  • 2021-06-02
  • 1970-01-01
  • 2020-01-08
  • 2020-11-18
  • 1970-01-01
  • 2017-06-13
  • 1970-01-01
  • 2020-03-20
相关资源
最近更新 更多