菜单
×
   ❮     
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 提供支持