class First extends React.Component{
handleClick(){
alert('handle click');
}
render(){
return <div>
<button onClick={this.handleClick}>click</button>
</div>;
}
}
在上面的示例中,为什么我们需要使用 this.handleClick 而不仅仅是 handleclick
不使用时
'handleClick' is not defined no-undef
感谢详细的解释
最佳答案
这不是 React 的东西。这是 JavaScript 的事。
如果没有 this.
,handleClick
是一个标识符引用,这意味着您必须有一个范围内声明的变量,名称为 handleClick
。你没有那个。您在名为 handleClick
的组件实例上有一个属性,但它不在任何范围内。
这与您在此处需要 this
的原因相同:
class Example {
constructor(value) {
this.value = value;
}
showValue() {
console.log(this.value); // <== Works
}
brokenShowValue() {
console.log(value); // <== ReferenceError, `value` is not defined
}
}
const e = new Example(42);
e.showValue();
e.brokenShowValue();
有 语言允许 this.
是隐式的(例如 Java 和 C#),但 JavaScript 不允许。
旁注:如果在某些时候您在 handleClick
中使用了 this
(您目前没有),请务必阅读 this question's answers .您需要做一些事情来确保正确的 this
在调用中可用(您的代码目前不会这样做)。
关于javascript - 在 Component 内部使用react,为什么我们需要使用 "this."来引用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50433195/