javascript - React子组件想要改变父组件的state,子组件中的两种写法为什么都能生效?
本文介绍了javascript - React子组件想要改变父组件的state,子组件中的两种写法为什么都能生效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
使用react时,我想要让子组件去触发更新父组件的state,我将setState方法写在了父组件中,然后通过props
向子组件中传递了这个方法,然后在子组件中通过绑定onClick事件触发this.props中传递进来的方法。在函数内部,我发现给this.props传进来的方法使用call(this)
时与不使用call,结果居然一样。
不是很明白为什么,通过绑定call之后,作用域应该已经改变了,并且是this指向子组件,但实际上指向的还是父组件。
百思不得其解,求大神指教!!!!!
代码:
这是绑定了call方法的
import React from 'react'
import ReactDOM from 'react-dom'
class ParentNode extends React.Component {
constructor(props) {
super(props);
this.state = {
msg: "start"
}
}
render() {
return (
<div>
这里是父组件 - {this.state.msg}
<div>
<ChildNode showMsg={this.changeMsg.bind(this)} />
</div>
</div>
)
}
changeMsg() {
console.log("-- parent this --", this);
this.setState({
msg: "end"
});
}
}
class ChildNode extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
点击此处查看效果<button onClick={this.changeMsgChild.bind(this)}>click me!!!</button>
</div>
)
}
changeMsgChild() {
console.log("-- changeMsgChild_this --", this);
this.props.showMsg.call(this);
}
}
ReactDOM.render(<ParentNode />, document.querySelector(".content"));
不绑定call的,就是将子组件中的showMsg方法的call方法去掉
changeMsgChild() {
console.log("-- changeMsgChild_this --", this);
this.props.showMsg(this);
}
最后其结果是一样的,都可以正常执行,而且都能改变父组件的state
解决方案
bind方法只有第一次bind时是有用的,得到的函数作用域已经确定,对这个函数无论再使用call,apply,bind都无法再改变其this值
这篇关于javascript - React子组件想要改变父组件的state,子组件中的两种写法为什么都能生效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文