The premise
The React element’s event handling is similar to that of the DOM element, with two differences:
- React events are named in a camelCase.
- To use JSX syntax you need to pass in a function as an event handler, not a string
Traditional writing:
<button onclick="activateLasers()">
Activate Lasers
</button>
Copy the code
The React of writing:
<button onClick={activateLasers}>
Activate Lasers
</button>
Copy the code
Pay attention to the point
- You cannot prevent the default behavior by returning false
The traditional writing
<a href="#" onclick="console.log('The link was clicked.'); return false">
Click me
</a>
Copy the code
The React of writing
Explicitly use preventDefault
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
Copy the code
- Methods in class do not bind this by default; they need to be explicitly bound
In JavaScript, class methods are not bound to this by default. If you forget to bind this.handleClick and pass it in onClick, this will be undefined when you call this function.