我有父组件:
state = {
value: 0
}
add() {
let { value } = this.state
value++
this.setState({ value: value})
}
remove() {
let { value } = this.state
value--
this.setState({ value: value})
}
render() {
return(
<Child add={this.add} remove={this.remove} />
)
}
和子组件:
...
render() {
const { add, remove } = this.props
return(
<div>
<button onClick={() => add()}>Add</button>
<button onClick={() => remove()}>Remove</button>
</div>
)
}
当我单击子组件内的按钮时,我想更新父组件中的value
状态。但是当我尝试以这种方式执行此操作时,我收到错误:
Cannot read property 'state' of undefined
我做错了什么?提前致谢。
最佳答案
出现问题是因为您的方法失去了与 this
的绑定(bind)。有两种方法可以解决这个问题。
箭头函数
使用 es6,您可以使用 arrow functions定义与 this
自动绑定(bind)的函数,如下所示:
add = () => {
let { value } = this.state
value++
this.setState({ value: value})
}
remove = () => {
let { value } = this.state
value--
this.setState({ value: value})
}
绑定(bind)函数
在组件的构造函数
中,您可以使用 bind
指定显式绑定(bind)函数,像这样:
constructor(props) {
super(props);
this.add = this.add.bind(this);
this.remove = this.remove.bind(this);
}
关于javascript - 从子组件更改父状态不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55811194/