ปฏิกิริยาเหตุการณ์
เช่นเดียวกับเหตุการณ์ HTML DOM React สามารถดำเนินการตามเหตุการณ์ของผู้ใช้
React มีเหตุการณ์เหมือนกับ HTML: click, change, mouseover เป็นต้น
กำลังเพิ่มกิจกรรม
เหตุการณ์ปฏิกิริยาเขียนด้วยไวยากรณ์ camelCase:
onClick
แทนonclick
.
ตัวจัดการเหตุการณ์ React นั้นเขียนอยู่ในวงเล็บปีกกา:
onClick={shoot}
แทน
onClick="shoot()"
.
ตอบสนอง:
<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>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
ผ่านข้อโต้แย้ง
หากต้องการส่งอาร์กิวเมนต์ไปยังตัวจัดการเหตุการณ์ ให้ใช้ฟังก์ชันลูกศร
ตัวอย่าง:
ส่ง "เป้าหมาย!" เป็นพารามิเตอร์ของshoot
ฟังก์ชันโดยใช้ฟังก์ชันลูกศร:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
ตอบสนองวัตถุเหตุการณ์
ตัวจัดการเหตุการณ์สามารถเข้าถึงเหตุการณ์ React ที่ทริกเกอร์ฟังก์ชันได้
ในตัวอย่างของเรา เหตุการณ์คือเหตุการณ์ "คลิก"
ตัวอย่าง:
ฟังก์ชั่นลูกศร: ส่งวัตถุเหตุการณ์ด้วยตนเอง:
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>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
สิ่งนี้จะมีประโยชน์เมื่อเราดูแบบฟอร์มในบทต่อๆ ไป