I have a hard time understanding react synthetic events.
The way I debug with native javascript events is something like this
window.addEventListener('mousemove',
function(event){
console.log(event);
})
If I move my mouse, and check the console, I can see the events properties such as target
and other useful properties such as innerHTML
, nextElementSibling
, lastChild
etc.
I have a simple react app below. Its an input field with a submit button. If something is entered in the input when submitted, an alert pops up. Otherwise nothing
// React Synthetic Events class AddOption extends React.Component { handleAddOption(e){ e.preventDefault(); console.log(e); const option = e.target.elements.option.value; // < HOW WOULD I FIND THIS IN THE DEBUGGER? if (option){ alert("something was entered in"); } } render() { return ( <div> <form onSubmit={this.handleAddOption}> <input type="text" name="option" /> <button>React Submit</button> </form> </div> ) } } ReactDOM.render(<AddOption />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"><!-- reactapp -->
What I don't get is if I inspect the page it doesn't give that useful information like I get with native events.
The issue is I referenced in my reactapp (following a tutorial) to use e.target.element.options.value
. I have no idea how someone would find that out in the debugger. I don't see a reference to anything dubbed element
in any of the long nested chain of prototype properties under synthetic event's target
. I tried CTRL+F but I don't think chrome supports searching nested prototypes
Am I not understanding something about things happening in the virtual DOM / react in general?
You can use e.nativeEvent
to get access to the native event and from there on to the elements.option.value
property:
// React Synthetic Events
class AddOption extends React.Component {
handleAddOption(e){
e.preventDefault();
console.log(e);
const option = e.target.elements.option.value; // < HOW WOULD I FIND THIS IN THE DEBUGGER?
// > YOU CAN USE e.nativeEvent TO GET ACCESS TO THE NATIVE EVENT:
console.log(e.nativeEvent);
console.log(e.nativeEvent.target.elements.option.value); // < HERE IS YOUR VALUE
if (option){
alert("something was entered in");
}
}
render() {
return (
<div>
<form onSubmit={this.handleAddOption}>
<input type="text" name="option" defaultValue={"Toy"}/>
<button>React Submit</button>
</form>
</div>
)
}
}
ReactDOM.render(<AddOption />, document.getElementById('root'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.