use*_*846 5 javascript ecmascript-6 reactjs
我已经看到了在类组件中声明方法的两种方法React
方法一
class someComp extends React.Component {
handleResetShapes = (e) => {
e.preventDefault();
this.setState({state: 'try'});
}
render() {}
}
Run Code Online (Sandbox Code Playgroud)
方法二
class someComp extends React.Component {
handleResetShapes(e) {
e.preventDefault();
this.setState({state: 'try'});
}
render() {}
}
Run Code Online (Sandbox Code Playgroud)
在那个特定的例子中Method 1有效,而另一个则无效。不过,我已经看到声明为的方法Method 2并且它工作正常,只是现在无法提供示例。
问题
有什么区别?这个 Javascript 概念叫什么?
方法1称为公共类字段语法,使用它我们不需要担心this运行时的含义,因为它是自动绑定的。例如:
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
在方法 2 中,它只是类上的普通方法,常见模式是使用ES6 类定义组件时的事件处理程序
但是,使用此方法时,您必须小心 JSX 回调中的含义this。在 JavaScript 中,默认情况下不绑定类方法。如果您忘记绑定this.handleClick并将其传递给onClick,在实际调用该函数时this将是未定义的。
class LoggingButton extends React.Component {
constructor(props) {
super(props);
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('this is:', this);
}
render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
Run Code Online (Sandbox Code Playgroud)
方法1和方法2的区别在于this实际调用函数时函数内部的含义。
参考:处理事件
| 归档时间: |
|
| 查看次数: |
3433 次 |
| 最近记录: |