简体   繁体   English

如何从子组件更改父状态?

[英]How to change parent state from child component?

I'm learning react.js and try to do something like this: I have NumberBox component with NumberLink child components. 我正在学习react.js并尝试执行以下操作:我有带有NumberLink子组件的NumberBox组件。

NumberBox has val state. NumberBox具有val状态。

NumberLink has val property. NumberLink具有val属性。

When I click NumberLink I'd like to change NumberBox state to link's val property, but in console I get: 当我单击NumberLink时,我想将NumberBox状态更改为链接的val属性,但是在控制台中,我得到:

Uncaught TypeError: this.props.onNumberLinkClick is not a function. 未捕获的TypeError:this.props.onNumberLinkClick不是函数。

Can you tell me what I am doing wrong? 你能告诉我我做错了什么吗? Here is the code: https://jsfiddle.net/ym58zcv4/1/ 这是代码: https : //jsfiddle.net/ym58zcv4/1/

You're passing undefined for the onNumberLinkClick prop. 您正在传递onNumberLinkClick道具的undefined

Use the second argument to Array.prototype.map() to provide the this value when the callback is executed: 执行回调时,请使用Array.prototype.map()的第二个参数提供this值:

var numberLinks = this.props.data.map(function (number) {
  return (
    <NumberLink val={number} key={number} onNumberLinkClick={this.handleNumberLinkClick}/>
  );
}, this)

Working fiddle: https://jsfiddle.net/ym58zcv4/3/ 工作提琴: https : //jsfiddle.net/ym58zcv4/3/


Using strict mode will turn cases like this into runtime errors so they're easier to catch. 使用严格模式会将类似这样的情况转换为运行时错误,因此更容易捕获。

You could also use ES6 arrow functions (which preserve the current value of this automatically) by enabling the React JSX transformer's harmony mode, or using Babel as your transpiler: 你也可以使用ES6箭头功能 (其中保留的当前值this通过启用阵营JSX变压器自动) harmony模式,或使用巴贝尔为您transpiler:

var numberLinks = this.props.data.map(number =>
  <NumberLink val={number} key={number} onNumberLinkClick={this.handleNumberLinkClick}/>
)

You were also setting the state round the wrong way in your handleNumberLinkClick function 您还在handleNumberLinkClick函数中以错误的方式设置了状态

this.setState({val:number}) should be this.setState({number:val}) this.setState({val:number})应该是this.setState({number:val})

https://jsfiddle.net/andykenward/6m3wp3kr/ https://jsfiddle.net/andykenward/6m3wp3kr/

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

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