Capítulo 20 de 116
Event handlers are functions defined inside a component and passed (never called) to a JSX tag as a prop; on custom components those prop names are entirely up to you, but browser events still bubble underneath, and stopPropagation()/preventDefault() are two unrelated tools for controlling that.
onClick={handleClick} — no parentheses, or it fires during render instead of on click.<button> only understands real browser event names (onClick), but your own component's prop can be named anything — convention is on + capitalized verb (onSmash, onPlayMovie), especially useful when a component supports several distinct interactions.<button> also fires onClick handlers on ancestor elements that have one, in order from the element outward.e.stopPropagation(): called on the event object inside a handler, stops the event from reaching ancestor handlers — use when a child's click shouldn't also trigger the parent's handler (e.g. a button inside a clickable toolbar).e.preventDefault(): stops the browser's default behavior for events that have one — e.g. a <form onSubmit> reloading the page by default. Unrelated to propagation: one stops handlers from firing, the other stops built-in browser behavior.function Button({ onClick, children }) {
return (
<button onClick={e => { e.stopPropagation(); onClick(); }}>
{children}
</button>
);
}
stopPropagation() used so a button's own click doesn't also trigger a parent container's click handler.onClick={handleClick}), never call it inline (onClick={handleClick()}) — the same rule from Ch 1, now with the "why": calling it fires immediately during render.stopPropagation() and preventDefault() solve different problems — don't reach for one when you mean the other.onSmash.