[英]How to bind a function's “this” to a class (React Component)
我有一个 function handleInputChange
,我想写一次(DRY 原则),但将它应用于我的许多 React 类。 但是,在构造函数中绑定到this
不起作用。
handleInputChange = (key, value) => {this.setState(key: value)}
class Login extends Component {
constructor(props) {
super(props);
this.state = {
loginBox: {
username: "",
password: ""}
}
this.handleInputChange = handleInputChange.bind(this) // DOESN't WORK
}}
为什么上述方法不起作用? 我得到的错误是:
Uncaught TypeError: Cannot read property 'setState' of undefined
我目前正在使用这个 function 包装解决方法,但我宁愿直接绑定 function。
handleInputChange = (_this) => () => (key, value) => {_this.setState(key: value)}
class Login extends Component {
...
this.handleInputChange = (key, value) => handleInputChange(this)(key, value)
您不能在箭头函数中绑定this
。 this
属于父 scope。
您可以将其设为非箭头 function:
function handleInputChange(key, value) { this.setState(key: value) }
但我建议在 class 上使用它。 定义引用this
的 function 很难阅读,因为您永远不知道this
在执行时会是什么,因此很难一目了然地阅读 function。
箭头函数没有自己的 this,如果你使用call([this obj], args)
, apply([this obj], args)
,任何“this”参数都会被忽略。 我想这同样适用于bind(obj)
,它不会将 this 绑定到您提供的 object ,因为它没有自己的 this 。
this
内部箭头函数由定义箭头 function 的词汇 scope 中的this
决定。 如果你在全局 scope 中定义你的handleInputChange
, this
里面是全局对象(在浏览器中它是窗口),这就是你得到错误的原因。
如果要使用bind
,可以像这样定义 function
function handleInputChange(key, value) { this.setState(key: value) }
当您调用bind
时, this
将设置为您在bind
中提供的 object。
由于您在 class 内部调用此 function ,因此最好将其定义为 class 内部的方法,而不是在外部定义它,这样this
问题就不那么重要了。
class 内部使其相当简单:
constructor(props) {
this.handleInputChange = this.handleInputChange.bind(this)
}
handleInputChange() {
//Code
}
或者,如果您想避免必须使用凌乱的bind
方法,您可以使用箭头 function 来表示该方法:
handleInputChange = () => {
console.log('This is: ', this);
}
...
render() {
return(
<button onClick={this.handleInputChange}>Click</button>
);
}
参考反应处理事件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.