在 onclick react 中传递函数名和通过回调调用有什么区别 [英] What is the difference between passing a function name in onclick react and calling it through callback
问题描述
我想知道 react 中这两个语句的区别.
I want to know the difference between these two statements in react.
<Button onClick={this.Callme}></Button>
<Button onClick={()=>this.Callme()}></Button>
它只是语法或者功能上也有任何区别.谢谢
Its just syntax or is there any difference in functionality too.Thanks
推荐答案
如果函数依赖于实例的调用上下文,并且函数尚未绑定到当前实例,则第一个代码将不起作用,因为 callMe
中的 this
将是 undefined
:
If the function depends on having a calling context of the instance, and the function isn't bound to the current instance already, the first code won't work, because the this
inside callMe
will be undefined
:
class Component extends React.Component {
name = 'component_name';
Callme() {
console.log(this.name);
}
render() {
return (
<button onClick={this.Callme}>Click</button>
);
}
}
// Render it
ReactDOM.render(
<Component />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
第二个代码有效,因为匿名箭头函数中的this
会从外部作用域继承this
,实例:
The second code works, because the this
in the anonymous arrow function will inherit the this
from the outer scope, the instance:
class Component extends React.Component {
name = 'component_name';
Callme() {
console.log(this.name);
}
render() {
return (
<button onClick={() => this.Callme()}>Click</button>
);
}
}
// Render it
ReactDOM.render(
<Component />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
如果 Callme
方法不需要引用实例,那么任一类型的 onClick
都可以工作.
If the Callme
method does not need to refer to the instance, then either type of onClick
works.
此常见问题的其他解决方案包括:
Other solutions to this common problem include:
- 在构造函数中绑定方法(
this.Callme = this.Callme.bind(this)
) - 设置回调时绑定方法(
onClick={this.Callme.bind(this)}>
) 将方法定义为构造函数中的箭头函数(或类字段),而不是原型的属性
- Binding the method in the constructor (
this.Callme = this.Callme.bind(this)
) - Binding the method when setting the callback (
onClick={this.Callme.bind(this)}>
) Defining the method as an arrow function in the constructor (or as a class field), rather than as a property of the prototype
class Component extends React.Component {
this.Callme = () => {
console.log(this.name);
}
这篇关于在 onclick react 中传递函数名和通过回调调用有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!