Javascript 反应更新子项';来自父组件的状态
当Javascript 反应更新子项';来自父组件的状态,javascript,reactjs,Javascript,Reactjs,当chartValue:true一个对象出现在图表上时 class Chart extends Component { constructor(props) { super(props); this.state = { chartValue: false, }; } componentWillReceiveProps(nextProps) { this.setState({ chartValue: nextProps
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>
);
}
}
类图扩展组件{
建造师(道具){
超级(道具);
此.state={
chartValue:false,
};
}
组件将接收道具(下一步){
这是我的国家({
chartValue:nextrops.chartValue
});
}
render(){
返回(
{this.state.chartValue}
);
}
}
我想通过我的应用程序组件中的按钮将该值更改为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>
)}
}
}
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state=({
chartValue:false,
});
}
callChartValue(){
这是我的国家({
chartValue:正确
})
}
render(){
返回(
呼叫
)}
}
}
在my App.js中更改状态似乎不会转换为图表组件状态的更改。我尝试过不使用componentWillReceiveProps,但也不起作用 代码中有两个主要问题: 1.你应该约束你的方法 否则,您将无法访问它们内部的
此
constructor(props) {
...
// Add this to your constructor
this.callChartValue = this.callChartValue.bind(this);
...
}
2.您不应该使用字符串来引用方法
render(){
返回(
...
//错
呼叫
//对
呼叫
...
)}
您的按钮不起作用。onClick应该是函数引用,而不是字符串。另外,如果您可以使用this.props.chartValue
,那么为什么需要在图表中包含状态?没错,我在编辑中更改了它。我是个新手,不知道我做得对不对。实际上,代码要复杂得多,this.props.chartValue
是Chart
的本机代码,需要远程更改。您可以查看我在react组件之间传递数据的答案:我应该添加您发布的绑定还是关闭我的react.createRef()
?谢谢你的回答。我只是删除了参考词以避免误解。干杯
render() {
return (
...
// Wrong
<button onClick="callChartValue">call</button>
// Right
<button onClick={this.callChartValue}>call</button>
...
)}