React 事件
与 HTML DOM 事件类似,React 也可以根据用户事件执行操作。
React 拥有与 HTML 相同的事件:click, change, mouseover 等。
添加事件
React 事件采用驼峰命名法
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
组件内
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
传递参数
要将参数传递给事件处理器,请使用箭头函数。
示例
使用箭头函数将“Goal!”作为参数传递给 shoot
函数
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
React 事件对象
事件处理器可以访问触发函数的 React 事件。
在我们的示例中,事件是“click”事件。
示例
箭头函数:手动发送事件对象
function Football() {
const shoot = (a, b) => {
alert(b.type);
/*
'b' represents the React event that triggered the function,
in this case the 'click' event
*/
}
return (
<button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Football />);
在后面的章节中介绍 表单 时,这将非常有用。