React 事件
与 HTML DOM 事件一样,React 可以根据用户事件执行操作。
React 具有与 HTML 相同的事件:单击、更改、鼠标悬停等。
添加事件
React 事件以 camelCase 语法编写:
用 onClick 替代 onClick
React 事件处理程序写在花括号内:
是 onClick={shoot}, 而不是 onClick="shoot()"
React:
<button onClick={shoot}>Take the Shot!</button>
HTML:
<button onclick="shoot()">Take the Shot!</button>
实例:
将 shoot 功能放在 Football 组件中:
import React from 'react';import ReactDOM from 'react-dom';function Football() {const shoot = () => {alert("Great Shot!");}return (<button onClick={shoot}>Take the shot!</button>);}ReactDOM.render(<Football />, document.getElementById('root'));
传递参数
要将参数传递给事件处理程序,请使用 arrow 函数。
实例:
使用箭头函数将 "Goal!" 作为参数发送到 shoot 函数
import React from 'react';import ReactDOM from 'react-dom';function Football() {const shoot = (a) => {alert(a);}return (<button onClick={() => shoot("Goal!")}>Take the shot!</button>);}ReactDOM.render(<Football />, document.getElementById('root'));
React 事件对象
事件处理程序可以访问触发函数的 React 事件。
在我们的示例中,事件是 "click" 事件。
实例:
箭头函数: 手动发送事件对象:
import React from 'react';import ReactDOM from 'react-dom';function Football() {const shoot = (a, b) => {alert(b.type);/*'b' 表示触发该功能的 React 事件。在这种情况下,'单击'事件*/}return (<button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>);}ReactDOM.render(<Football />, document.getElementById('root'));
当我们在后面的章节中学习 React Form 表单时,这将非常有用。