es6 - React.js中定义静态方法,不确定this
本文介绍了es6 - React.js中定义静态方法,不确定this的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
下面是一段简略的代码:我想通过外部调用静态方法,设置this.setState
class Box extends React.Component {
...
static update(user) {
this.setState({
onlineuser: user
})
}
...
}
Box.update(user);
console提示:this.update is not a function
怎么正确绑定this呢?
试了Stack里面的几种方法还是不行
http://stackoverflow.com/questions/33381756/this-setstate-is-not-a-function
http://stackoverflow.com/questions/31045716/react-this-setstate-is-not-a-function
解决方案
首先,我已经也试了几种方法绑定this。 还是报错。
然后认真读了官方给出的使用静态方法时的问题。
https://facebook.github.io/react/docs/component-specs.html
the methods do not have access to the props or state of your components. 这里说react默认不能通过静态方法设置state。
这篇关于es6 - React.js中定义静态方法,不确定this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文