使用 JSX 语法在 ReactJS 组件中定义事件处理程序有不同的方法。
<input onChange={this.handleChange.bind(this)}></input> // inline binding
还有
<input onChange={() => this.handleChange()}></input> // using arrow function
两者都允许handleChange
函数访问组件的this
范围。
我一直使用第一种语法,因为它的可读性更清晰。
使用其中一种相对于另一种是否有任何优势或用例?
最佳答案
class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
// This syntax ensures `this` is bound within handleClick
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
);
}
}
The problem with this syntax is that a different callback is created each time the LoggingButton renders. In most cases, this is fine. However, if this callback is passed as a prop to lower components, those components might do an extra re-rendering. We generally recommend binding in the constructor or using the property initializer syntax, to avoid this sort of performance problem.
因此,您应该使用bind
,并且可以通过两种方式实现这一点。
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(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
如果bind
让你烦恼,那么你可以这样做
class LoggingButton extends React.Component {
// This syntax ensures `this` is bound within handleClick.
// Warning: this is *experimental* syntax.
handleClick = () => {
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
我能想到使用其中一种方法相对于另一种方法的唯一优点是,在顶级方法中,您可以将参数传递给 handleClick
函数。但我想不出在什么情况下你可以这样做。
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
}
handleClick(e, something) {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
alert(something)
}
render() {
return (
<button onClick={(e) => this.handleClick(e, "Yo!")}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
关于javascript - 在 ReactJS 组件中定义事件处理程序的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45690110/