使用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 (
这里是父组件 - {this.state.msg}
)
}
changeMsg() {
console.log("-- parent this --", this);
this.setState({
msg: "end"
});
}
}
class ChildNode extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
点击此处查看效果
)
}
changeMsgChild() {
console.log("-- changeMsgChild_this --", this);
this.props.showMsg.call(this);
}
}
ReactDOM.render( , document.querySelector(".content"));
不绑定call的,就是将子组件中的showMsg方法的call方法去掉
changeMsgChild() {
console.log("-- changeMsgChild_this --", this);
this.props.showMsg(this);
}
最后其结果是一样的,都可以正常执行,而且都能改变父组件的state
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
bind方法只有第一次bind时是有用的,得到的函数作用域已经确定,对这个函数无论再使用call,apply,bind都无法再改变其this值