简体   繁体   English

反应从父组件更新孩子的状态

[英]React Update Child's state from Parents Component

When chartValue: true an object appears on the chart.chartValue: true对象出现在图表上时。

class Chart extends Component {
  constructor(props) {
    super(props);

     this.state = {
       chartValue: false,
     };
   }

  componentWillReceiveProps(nextProps) {
    this.setState({
      chartValue: nextProps.chartValue
    });
  }

  render() {
    return (
      <div>{this.state.chartValue}</div>
    );
  }
}

I want to change the value to true via a button in my app component.我想通过我的应用程序组件中的按钮将值更改为 true。

class App extends Component {
  constructor(props) {
    super(props);

    this.state = ({
       chartValue: false,
    });
  }

  callChartValue() {
    this.setState({
      chartValue: true
    })
  }

  render() {
    return (
       <div>
         <button onClick={this.callChartValue}>call</button>
         <Chart chartValue={this.state.chartValue} />
       </div>
    )}
  }
}

It seems like changing the state in my App.js doesnt translate to a change in the state of the chart component.似乎改变我的 App.js 中的状态并没有转化为图表组件状态的改变。 I've tried without using componentWillReceiveProps but it hasn't worked either.我试过不使用 componentWillReceiveProps 但也没有用。

You have two main issues in your code:您的代码中有两个主要问题:

1. You should bind your methods 1. 你应该绑定你的方法

Otherwise, you won't have access to this inside them.否则,您将无法在其中访问this内容。

constructor(props) {

  ...

  // Add this to your constructor
  this.callChartValue = this.callChartValue.bind(this);

  ... 
}

2. You shouldn't use strings for referencing the methods 2. 你不应该使用字符串来引用方法

render() {
  return (

    ...

     // Wrong
     <button onClick="callChartValue">call</button>

     // Right
     <button onClick={this.callChartValue}>call</button>

    ...

)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM