[英]What is the best way to call a handling function in React?
I was reading the ReactJs documentation about Handling events and I wondered what the best practice is for calling a handling function in a component.我正在阅读有关处理事件的ReactJs 文档,我想知道在组件中调用处理 function 的最佳做法是什么。
My question is very simple (and even basic I think): what should be used between onClick={handleClick}
or onClick={this.handleClick]
?我的问题很简单(我认为甚至是基本的):在onClick={handleClick}
或onClick={this.handleClick]
之间应该使用什么?
I wonder after seeing these two pieces of code in which handleClick
is called without the keyword this
in the first code and with in the second code.在看到这两段代码后,我想知道在第一个代码中没有关键字this
而在第二个代码中调用了handleClick
。
ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
They are 2 different situations.他们是两种不同的情况。
onClick={handleClick}
is used in functional component, in a function this
key work is refer to the place when the function is call, you don't use this
in functional component. onClick={handleClick}
用于功能组件,在 function 中this
关键工作是指调用 function 时的地方,你不要在功能组件中使用this
。onClick={this.handleClick]
is used in class component. onClick={this.handleClick]
用于 class 组件。 In class you need to use this
key work to access class property which is function in this case.在 class 中,您需要使用this
关键工作来访问 class 属性,在这种情况下为 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.