【发布时间】:2021-10-18 04:16:32
【问题描述】:
function Parent() {
const [value, setValue] = React.useState("");
function handleChange(newValue) {
setValue(newValue);
}
// We pass a callback to Child
return <Child value={value} onChange={handleChange} />;
}
function Child(props) {
function handleChange(event) {
// Here, we invoke the callback with the new value
props.onChange(event.target.value);
}
return <input value={props.value} onChange={handleChange} />
}
这里是参考文章https://webomnizz.com/change-parent-component-state-from-child-using-hooks-in-react。我的问题是我们是否可以直接将 setValue 传递给子组件的 onChange ?哪种方式是最佳实践?谢谢
function Parent() {
const [value, setValue] = React.useState("");
// We pass setValue directly to Child
return <Child value={value} onChange={setValue} />;
}
【问题讨论】:
-
当然可以,甚至更易读