Events
Respond to user actions with event handlers and keep side effects outside rendering.
Event handlers run in response to interaction, making them the right place for updates, navigation commands, and other effects caused by a specific action.
Pass a function
CourseCard.tsx
function CourseCard({ course, onOpen }) {
function handleOpen() {
onOpen(course.slug);
}
return <button onClick={handleOpen}>Open {course.title}</button>;
}
Pass handleOpen, not handleOpen(). Props can carry event handlers upward so the component that owns state decides how it changes.
Event propagation
Toolbar.tsx
<div onClick={() => log("toolbar click")}>
<button onClick={(event) => { event.stopPropagation(); save(); }}>Save</button>
</div>
Events bubble. Stop propagation only when the nested action genuinely should not trigger its ancestor. Use preventDefault() only when replacing a browser default such as form navigation.
Keep this
Pass handlers as values, let state owners handle updates, and preserve browser defaults unless the component fully replaces them.
学习位置已保存在此设备上。