【问题标题】:React JS 'this' not working as expectedReact JS 'this' 没有按预期工作
【发布时间】:2017-04-04 02:36:32
【问题描述】:

我有以下代码

save: function() {
        var _this = this;

        console.log(this.refs.itemText)

        this.setState({isEditing : false}, 
            function() {
                console.log("Inside call back");
                console.log(_this.refs);
                console.log(_this.refs.itemText);
             }   
        );    
    },

但是 _this 在回调函数中是不可访问的。这是范围问题吗?

查看演示here

【问题讨论】:

  • 可能,但这取决于。你能分享一下你调用save方法的方式和地点吗?
  • @KaloyanKosev 我已经添加了 codepen 演示
  • @abhirathore2006 并非如此,因为@phpsessionid 使用的是React.createClass 语法。
  • @phpsessionid 感谢codepen,我添加了答案。

标签: javascript reactjs


【解决方案1】:

使用 refs 的正确位置是在特定的 React lifecycle methods 中,例如ComponentDidMount,ComponentDidUpdate。

在您的情况下,如果您想在状态更改后立即执行某些操作,请连接 componentDidUpdate 方法(而不是使用 this.setState 回调)。

阅读更多关于the cautions of working with refs here的信息。

【讨论】:

    【解决方案2】:

    我检查了您的代码,一切正常。问题出在你的逻辑上。

    让我解释一下出了什么问题。

    1. 当您处于编辑模式时,您的 itemText 会被渲染,因此它可以在 refs 中使用,从而显示正确的控制台日志。

    2. 当您保存并更改状态时,它会重新呈现表单,并且由于您的状态已更改,您的输入元素现在已隐藏。因此,当您尝试访问其引用时,它会返回 undefined。

    我希望这能回答你的问题。

    【讨论】:

      猜你喜欢
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多