需要注意的两点:1.需要在事件绑定的函数中获取事件对象 2.事件绑定函数中的this指向问题
疑惑点:什么是public class fields语法
一、事件对象作为参数传递
事件绑定的函数没有传参
function ActionLink() {
function handleClick(e) { // 默认有一个事件对象参数,而且是经过包装的不会有兼容性问题
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
事件绑定的函数需要传参
此时分为两种情况来获取事件对象
1.通过箭头函数
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
2.通过Function.prototype.bind()方法
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
二、this指向问题
构造函数中通过bind绑定this
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 为了在回调中使用 `this`,这个绑定是必不可少的
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')
);
class LoggingButton extends React.Component {
handleClick = () => {
console.log('this is:', this);
}
render() {
// 此语法确保 `handleClick` 内的 `this` 已被绑定。
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
回调中使用箭头函数
class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
// 此语法确保 `handleClick` 内的 `this` 已被绑定。
return (
<button onClick={() => this.handleClick()}>
Click me
</button>
);
}
}