[英]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:您的代码中有两个主要问题:
Otherwise, you won't have access to this
inside them.否则,您将无法在其中访问
this
内容。
constructor(props) {
...
// Add this to your constructor
this.callChartValue = this.callChartValue.bind(this);
...
}
render() {
return (
...
// Wrong
<button onClick="callChartValue">call</button>
// Right
<button onClick={this.callChartValue}>call</button>
...
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.