- React 事件的命名采用驼峰式。
- 使用 JSX 时需要传入一个函数作为事件处理函数,而不是字符串。
传统 HTML:
<button onclick="submit()"></button>
React:
<button onClick="{submit}"></button>
Angular:
<button (click)="submit()"></button>
- 在 React 中,不能通过返回 false 来阻止默认行为。必须显式地使用 preventDefault()方法。
传统 HTML:
<a href="#" onclick="console.log('Hello'); return false"></a>
React:
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log("The link was clicked");
}
return (
<a href="#" onClick={handleClick}>
CLick me
</a>
);
}
e 是一个合成事件。React 根据 W3C 规范来定义合成事件,不需要担心跨浏览器的兼容性问题。
使用 React 时,一般不需要使用 addEventListener 为已创建的 DOM 元素添加监听器。只需要在该元素初始渲染的时候添加监听器即可。
定义 class 组件时,通常将事件处理函数声明为 class 中的方法:
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>
);
}
}
ReactDOM.render(<Toggle />, document.getElementById("root"));
在 JavaScript 中,class 方法默认不会绑定 this。所以在 onClick 里调用回调函数 this.handleClick 时,一定要记得让 this.handleClick 绑定 this。否则调用这个函数时,this 的值为 undefined。
如果没有在方法后面添加 (),例如 onClick={this.handleClick},应该为这个方法绑定 this。
添加了()就不用绑定 this 吗?
这个绑定可能有点麻烦,解决方法一是使用箭头函数:
class LoggingButton extends React.Component {
handleClick() {
console.log("this is:", this);
}
render() {
// 此语法确保 `handleClick` 内的 `this` 已被绑定。
return <button onClick={() => this.handleClick()}>Click me</button>;
}
}
此语法问题在于每次渲染 LoggingButton 时都会创建不同的回调函数。在大多数情况下,这没什么问题,但如果该回调函数作为 prop 传入子组件时,这些组件可能会进行额外的重新渲染。所以建议不要偷懒。
向事件处理程序传递参数
在循环中,通常我们会为事件处理函数传递额外的参数。例如,若 id 是你要删除那一行的 ID,以下两种方式都可以向事件处理函数传递参数:
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
上述两种方式是等价的,分别通过箭头函数和 Function.prototype.bind 来实现。 第一种,React 的事件对象 e 会被作为第二个参数传递,通过箭头函数的方式,事件对象必须显式的进行传递。而通过 bind 的方式,事件对象以及更多的参数将会被隐式的进行传递。