[英]Can't pass a head of a method to event handling in React markup
在我的render()中,我具有以下用于事件处理的组件。
render() { ...
<input type="text"
onChange={(_) => { this.restate("email", _.target.value); }} />
}
private restate(type: string, input: any) { ...
if (type === "email")
this.setState({ ... });
}
这可以正常工作并表现出预期的效果。 由于我现在正在学习React,因此我尝试改善语法,以使它看起来很平滑。 我找到了这个答案,并且喜欢事件处理程序分配的简洁性。 因此,我更改了渲染并实现了要按以下方式传递的处理程序。
render() { ...
<input type="text" onChange={ this.handleEmail } />
}
private handleEmail(data: React.ChangeEvent<HTMLInputElement>) {
console.log("hit before: " + data.target.value);
console.log(this);
this.restate("email", data.target.value);
}
标记中的更改似乎起作用,因为调用了handleEmail(...)方法。 但是,我收到一条错误消息,说restate(...)不是未定义的方法,实际上,当我调查这是什么时,我发现它是未定义的 。
我需要帮助,以了解我在做什么错以及它与上面链接的文章有何不同。 我试图用谷歌搜索React版本之间的语法差异,但一无所获。 我不确定如何用正确的技术术语来描述问题。
我认为您应该做的是
render() { ...
<input type="text" onChange={(e) => this.handleEmail(e) } />
}
我认为您的重述方法不是undefined
方法的原因是因为您的方法未绑定到组件。 为了使您的方法成为react类的一部分,您需要将该方法绑定到该类。 有几种方法可以做到这一点。 在这样的类构造函数中:
constructor(props) {
super(props);
this.handleEmail = this.handleEmail.bind(this);
}
或内部渲染功能,如我上面所示。 第三是像这样在类体内使用arrow函数:
handleEmail = () => {
// call this function from render
// and this.whatever in here works fine.
};
为了在onClick函数中使用this
函数,您需要将其绑定到构造函数中。 您也可以在render()
使用bind,但是不建议这样做,因为bind
将被多次调用。 react docs建议像这样在构造函数内部使用bind
constructor() {
super();
this.handleEmail = this.handleEmail.bind(this);
}
这并不是React的JavaScript所特有的。 其设计。
这是bind
作用
bind()方法创建一个新函数,该函数在被调用时将其关键字设置为提供的值,并在调用新函数时提供给定的参数序列。
题
为什么第一个示例起作用?
render() { ...
<input type="text"
onChange={(_) => { this.restate("email", _.target.value); }} />
}
这是因为您使用了ES6箭头功能()=> {}
。 这也称为胖箭头功能。
当你使用箭头功能, this
从包围上下文中获取,你可以使用this
自己的函数中没有约束力。 这就是为什么第一个示例起作用的原因。
如果您使用了第二个示例,则该示例将起作用
render() { ...
<input type="text" onChange={ ()=> this.handleEmail() } />
}
我建议阅读这篇出色的文章,以获取有关bind
更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.