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 />);
在後面的章節中介紹 表單 時,這將非常有用。