Reactjs 哪个对象拥有单击处理程序代码?
我知道,当使用React类方法时,箭头函数是锁定Reactjs 哪个对象拥有单击处理程序代码?,reactjs,typescript,onclick,this,Reactjs,Typescript,Onclick,This,我知道,当使用React类方法时,箭头函数是锁定此的好方法。例如,我可能有一个单击处理程序: clickHandler = () => { // some code using 'this' // eg this.state } // ... and in the render method <button onClick={() => this.clickHandler()}>Test Button</button> 您的“this”将是
此
的好方法。例如,我可能有一个单击处理程序:
clickHandler = () => {
// some code using 'this'
// eg this.state
}
// ... and in the render method
<button onClick={() => this.clickHandler()}>Test Button</button>
您的“this”将是“未定义”的,因为React在幕后调用您的函数,而它不会从对象实例调用它(即MyComponent.onClickHandler(E)
),它会这样调用它(onClickHandler(E))
一个没有反应的简化模型看起来是这样的
class FakeReactComponent {
myName() {
console.log(this);
}
}
// this is what you give a onClick prop on an element.
const functionPassedToOnClick= new FakeReactComponent().myName;
console.log(
functionPassedToOnClick() // this is how react calls it (this is undefined)
)
解决这个问题的方法是在组件的构造函数中绑定函数的“this”,即
constructor(props: IProps) {
super(props);
this.onClickHandler = this.onClickHandler.bind(this);
}
这实际上是为React组件定义类中所有函数的“最佳实践”方法,因为箭头函数不在类原型上,因此为该组件的每个新React实例创建新函数;但是,使用非箭头函数时,每个实例都会在原型上运行,因此会被每个react组件实例重用
像自动绑定这样的技巧也不是最佳实践,因为绑定每个函数的this
是不必要的,因为只有React调用的函数需要绑定它们的this
,并且99%的时间只有函数被用作事件处理程序。这取决于调用函数的方式以及是否需要把它绑起来
class Test extends React.Component {
clickHandler = function() {
console.log(this);
}
render() {
return (
<div>
<button onClick={this.clickHandler}>Option A</button>
<button onClick={this.clickHandler.bind(this)}>Option B</button>
<button onClick={() => this.clickHandler()}>Option C</button>
</div>
);
}
}
在这种情况下,Test.clickHandler()
中的this
实际上是对按钮
实例的引用。谢谢。如果其他人不明白“未定义”为什么会出现在这里,就像我一样,那么请检查此项:
class Test extends React.Component {
clickHandler = function() {
console.log(this);
}
render() {
return (
<div>
<button onClick={this.clickHandler}>Option A</button>
<button onClick={this.clickHandler.bind(this)}>Option B</button>
<button onClick={() => this.clickHandler()}>Option C</button>
</div>
);
}
}
class Button extends React.Component {
render() {
return (
<button
onClick={this.props.onClick.bind(this)}
children={this.props.children}
/>
);
}
}
class Test extends React.Component {
clickHandler = function() {
console.log(this);
}
render() {
return <Button onClick={this.clickHandler}>Click</Button>;
}
}