Menu
×
   ❮     
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 />);

运行示例 »

在我们以后的章节中学习 表单 时,这将非常有用。



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.