प्रतिक्रिया घटनाक्रम
HTML DOM ईवेंट की तरह, रिएक्ट उपयोगकर्ता की घटनाओं के आधार पर कार्रवाई कर सकता है।
रिएक्ट में HTML जैसी ही घटनाएँ होती हैं: क्लिक, चेंज, माउसओवर आदि।
ईवेंट जोड़ना
प्रतिक्रिया घटनाएँ कैमलकेस सिंटैक्स में लिखी जाती हैं:
onClick
के बजाय onclick
।
रिएक्ट इवेंट हैंडलर घुंघराले ब्रेसिज़ के अंदर लिखे गए हैं:
onClick={shoot}
के बजाय
onClick="shoot()"
।
प्रतिक्रिया:
<button onClick={shoot}>Take the Shot!</button>
एचटीएमएल:
<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'));
प्रमाणन हासिल करें!
$95 नामांकन
पासिंग तर्क
किसी ईवेंट हैंडलर को तर्क पास करने के लिए, तीर फ़ंक्शन का उपयोग करें।
उदाहरण:
भेजें "लक्ष्य!" फ़ंक्शन के पैरामीटर के रूप में shoot
, एरो फ़ंक्शन का उपयोग करके:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
प्रतिक्रिया घटना वस्तु
इवेंट हैंडलर के पास रिएक्ट इवेंट तक पहुंच होती है जिसने फ़ंक्शन को ट्रिगर किया।
हमारे उदाहरण में घटना "क्लिक" घटना है।
उदाहरण:
एरो फंक्शन: इवेंट ऑब्जेक्ट को मैन्युअल रूप से भेजना:
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'));
यह तब काम आएगा जब हम बाद के अध्याय में फॉर्म को देखेंगे।