DOM इवेंट्स के आदेश पर: CAPTURING vs BUBBLING
घटनाओं के प्रचार के लिए दो चरण हैं। इन्हें "कैप्चरिंग" और "बबलिंग" कहा जाता है ।
| | / \
---------------| |----------------- ---------------| |-----------------
| element1 | | | | element1 | | |
| -----------| |----------- | | -----------| |----------- |
| |element2 \ / | | | |element2 | | | |
| ------------------------- | | ------------------------- |
| Event CAPTURING | | Event BUBBLING |
----------------------------------- -----------------------------------
कैप्चरिंग स्टेज पहले होता है, और उसके बाद बबलिंग स्टेज होता है। जब आप नियमित DOM एपीआई का उपयोग करके किसी घटना को पंजीकृत करते हैं, तो ईवेंट डिफ़ॉल्ट रूप से बबलिंग चरण का हिस्सा होगा, लेकिन यह ईवेंट निर्माण पर निर्दिष्ट किया जा सकता है
// CAPTURING event
button.addEventListener('click', handleClick, true)
// BUBBLING events
button.addEventListener('click', handleClick, false)
button.addEventListener('click', handleClick)
प्रतिक्रिया में, बुदबुदाती घटनाएँ भी हैं जो आप डिफ़ॉल्ट रूप से उपयोग करते हैं।
// handleClick is a BUBBLING (synthetic) event
<button onClick={handleClick}></button>
// handleClick is a CAPTURING (synthetic) event
<button onClickCapture={handleClick}></button>
आइए एक नज़र डालते हैं हमारे हैंडल पर क्लिक करें कॉलबैक (प्रतिक्रिया):
function handleClick(e) {
// This will prevent any synthetic events from firing after this one
e.stopPropagation()
}
function handleClick(e) {
// This will set e.defaultPrevented to true
// (for all synthetic events firing after this one)
e.preventDefault()
}
एक विकल्प जो मैंने यहाँ नहीं देखा है
यदि आप अपने सभी ईवेंट में e.preventDefault () कहते हैं, तो आप देख सकते हैं कि क्या कोई ईवेंट पहले ही हैंडल किया जा चुका है, और इसे फिर से हैंडल करने से रोकें:
handleEvent(e) {
if (e.defaultPrevented) return // Exits here if event has been handled
e.preventDefault()
// Perform whatever you need to here.
}
सिंथेटिक घटनाओं और देशी घटनाओं के बीच अंतर के लिए, प्रतिक्रिया दस्तावेज देखें: https://reactjs.org/docs/events.html