This is the 19th day of my participation in the Genwen Challenge
React event handling
- React events are named with the small hump. The instance of the small hump is onClcik
- Traditional HTML event handlers pass in a string
<button onclick="activateLasers()">
Activate Lasers
</button>
Copy the code
- React event handling is wrapped in braces
<button onClick={activateLasers}>
Activate Lasers
</button>
Copy the code
- In React, preventDefault must be allowed, not return false.
Traditional HTML prevents the default submission behavior of forms.
<form onsubmit="console.log('You clicked submit.'); return false">
<button type="submit">Submit</button>
</form>
Copy the code
React prevents forms from submitting by default
function Form() {
function handleSubmit(e) {
e.preventDefault();
console.log('You clicked submit.');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
Copy the code
- React listens on DOM elements, usually not through an addEventListener. It’s through methods in the component.
- Be careful with this in JSX syntax. The class method does not bind this by default. To solve this problem, we usually use arrow functions in callback functions.
class LoggingButton extends React.Component {
handleClick() {
console.log('this is:'.this);
}
render() {
// This syntax ensures that 'this' in' handleClick 'is bound.
return (
<button onClick={()= > this.handleClick()}>
Click me
</button>); }}Copy the code
Pass parameters to the event handler
Official description: In loops, we usually pass extra arguments to event handlers. For example, if id is the ID of the row you want to delete, you can pass arguments to the event handler in either of the following ways.
<button onClick={(e) = > this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)} >Delete Row</button>
Copy the code
- The two approaches above are equivalent, either through the arrow function or through bind to the this in the JSX callback and pass in the argument.
Official description: In both cases, the React event object e is passed as the second argument. If the arrow function is used, the event object must be passed explicitly, whereas if bind is used, the event object and more parameters are passed implicitly.
Interpretation of the
- With the arrow function, the event object needs to be passed explicitly, whereas with bind, it can be passed implicitly.
Please check out the React document for updates daily.