侧边栏壁纸
博主头像
忆全栈 博主等级

行动起来,活在当下

  • 累计撰写 3 篇文章
  • 累计创建 2 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

React 事件

忆全栈
2026-06-03 / 0 评论 / 0 点赞 / 6 阅读 / 0 字

事件处理

事件小驼峰法则

  • 传统的HTML
<button onclick="activateLasers()">按钮</button>
  • 而在React则不同
function Order() {
  // 事件处理函数
  const activateLasers = () => {
    console.log("Lasers are on!");
  };
  // 渲染组件
  return (
    <div>
      <h1>Hello</h1>
      <h2>Good to see you </h2>
      <button onClick={activateLasers}> 按钮</button>
    </div>
  );
}

向事件里面传递函数

function Order() {
  // 事件处理函数
  const activateLasers = (args1) => {
    console.log(args1);
  };
  // 渲染组件
  return (
    <div>
      <h1>Hello</h1>
      <h2>Good to see you </h2>
      <button onClick={() => activateLasers("哈哈哈")}> 按钮</button>
    </div>
  );
}

阻止默认事件

  • 第一个参数就是e,后面要是有多余的参数往后延
function Order() {
  // 事件处理函数
  const activateLasers = (e, args1) => {
    e.preventDefault();
    console.log("Lasers are on!", args1);
  };
  // 渲染组件
  return (
    <div>
      <h1>Hello</h1>
      <h2>Good to see you </h2>
      <button onClick={(e) => activateLasers(e, "自定义参数")}> 按钮</button>
    </div>
  );
}

注意事项

  • React 事件的命名采用小驼峰法则,而不是纯小写

  • React 事件里面必须重新绑定 this 指向,否则会指向 window 或者使用箭头函数

  • 使用 JSX 语法时候你需要传一个函数作为事件处理函数,而不是一个字符串

  • React 中 不能返回 false 来阻止默认行为,你必须使用 e.preventDefault()来阻止,如:提交表单时,阻止表单默认提交

0
博主关闭了所有页面的评论