javascript - React子组件想要改变父组件的state,子组件中的两种写法为什么都能生效?
大家讲道理
大家讲道理 2017-04-11 12:16:55
[JavaScript讨论组]

使用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

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(1)
PHP中文网

bind方法只有第一次bind时是有用的,得到的函数作用域已经确定,对这个函数无论再使用call,apply,bind都无法再改变其this值

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号