首页 文章

在一个反应组件中,如何在静态函数中得到`this`?

提问于
浏览
7

尝试在react组件中创建 static 函数 . 该函数使用 this 来获取其数据,但 this 在调用函数时超出范围 .

这是一个非常简单的例子:

var Test = React.createClass({
  val: 5,
  statics: {
    getVal: function() { return this.val }
  },
  render: return( <div>{this.val}</div> )
});

Test.getVal(); => undefined!!

显然 this 在调用 Test.getVal() 时失去了它的范围 . 如何在 getVal() 函数中获取 this

fyi,以下标准的javascript父方法不起作用:

Test.getVal.apply( Test ); => undefined

2 回答

  • 0

    看看the docs on statics .

    无论你在 statics 中放置什么都不会有实际的React组件实例的上下文,但是 val 属性在实际渲染组件之前不会存在,因为那是构造所有非静态属性的时候 . 静态应该是与实际实例的上下文之外可用的组件相关的函数,就像例如C#中的静态函数和许多其他语言一样 .

    想要从 statics 函数访问React组件实例似乎没有意义 . 也许你需要考虑你的're actually trying to achieve. If you really want to be able to access a specific component'属性,然后我猜你可以将实例作为参数传递给静态函数,但当然,一旦你实际构建了一个组件,它就可以使用了 .

  • 9

    啊,好吧误会 . 如果你需要以某种方式调用这个方法,那么你的val也必须位于静态中,但你的渲染函数必须引用Test.val而不是this.val . 如果这不是一个要求,尽管最好坚持使用props / state并从组件内部访问东西,因为组件不会根据val的更改自动更新 .

    var Test = React.createClass({
      statics: {
        val: 5,
        getVal: function() { 
            return this.val
        }
      },
      render: function(){
          return( <div>{Test.val}</div> )
      }
    });
    
    console.log('VAL IS' , Test.getVal());
    

    链接到小提琴示例https://jsfiddle.net/dgoks3Lo/

相关问题