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

时间:2020-02-01 20:44:46

标签: javascript reactjs

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>
    );
  }
}

我想通过我的应用程序组件中的按钮将值更改为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>
    )}
  }
}

似乎更改App.js中的状态不会转换为图表组件状态的更改。我尝试过不使用componentWillReceiveProps,但是它也没有起作用。

1 个答案:

答案 0 :(得分:0)

您的代码中存在两个主要问题:

1。您应该绑定方法

否则,您将无法访问其中的this

constructor(props) {

  ...

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

  ... 
}

2。您不应该使用字符串来引用方法

render() {
  return (

    ...

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

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

    ...

)}