事件处理
事件小驼峰法则
- 传统的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()来阻止,如:提交表单时,阻止表单默认提交