選單
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

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 />);

執行示例 »


w3schools CERTIFIED . 2022

獲得認證!

完成 React 模組,完成練習,參加考試,並獲得 w3schools 認證!

$95 註冊

傳遞引數

要將引數傳遞給事件處理器,請使用箭頭函式。

示例

使用箭頭函式將“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 />);

執行示例 »

在後面的章節中介紹 表單 時,這將非常有用。



×

聯絡銷售

如果您想將 W3Schools 服務用於教育機構、團隊或企業,請傳送電子郵件給我們
sales@w3schools.com

報告錯誤

如果您想報告錯誤,或想提出建議,請傳送電子郵件給我們
help@w3schools.com

W3Schools 經過最佳化,旨在方便學習和培訓。示例可能經過簡化,以提高閱讀和學習體驗。教程、參考資料和示例會不斷審查,以避免錯誤,但我們無法保證所有內容的完全正確性。使用 W3Schools 即表示您已閱讀並接受我們的使用條款Cookie 和隱私政策

版權所有 1999-2024 Refsnes Data。保留所有權利。W3Schools 由 W3.CSS 提供支援