英文:
React set initial state from parent and updates in child should propagate to parent
问题
当子组件需要从父组件派生其初始状态,但用户也可以更改子组件的状态值,需要将这些更改传播回父组件时,应如何处理案例?
简化示例:
const Child = (props) => {
const { parentProperty, dispatch } = props;
const [localValue, setLocalValue] = useState(parentProperty); //仅在初始渲染时调用此行。
useEffect(() => {
setLocalValue(parentProperty); //这不会引发循环循环吗?父->子->父?
}, [parentProperty]);
useEffect(() => {
dispatch({ type: "CHILD_PROP_CHANGE", localValue }); //需要将localValue用户更改传播回父组件
}, [localValue]);
return (
<div>
<input
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
/>
</div>
);
};
英文:
How should the case be handled when a child component needs to derive its initial state from the parent, but user can also change value of the state in the child and this needs to be propagated back up to the parent?
Simplified example:
const Child = (props) => {
const { parentProperty, dispatch } = props;
const [localValue, setLocalValue] = useState(parentProperty); //this line only gets called in the initial render.
useEffect(() => {
setLocalValue(parentProperty); //doesn't this cause circular loop? parent->child->parent?
}, [parentProperty]);
useEffect(() => {
dispatch({ type: "CHILD_PROP_CHANGE", localValue }); //need to propagate localValue user change back to parent
}, [localValue]);
return (
<div>
<input
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
/>
</div>
);
};
答案1
得分: 1
为了在React中在父组件和子组件之间同步状态,您可以将状态提升到父组件,并将其作为属性传递给子组件。属性是一种向另一个组件传递数据的方式。您还可以将函数作为属性传递,这样子组件可以使用它将数据发送回父组件。这使得父组件可以管理状态,而子组件可以显示和更改它。
例如:
const Child = ({ value, onChange }) => {
return (
<div>
<input value={value} onChange={onChange} />
</div>
);
};
const Parent = () => {
const [value, setValue] = useState("")
const handleChangeValue = (e) => {
setValue(e.target.value)
}
return (
<Child value={value} onChange={handleChangeValue} />
)
}
要了解更多信息,请参阅在组件之间共享状态。
英文:
To sync state between parent and child components in React, you can lift the state up to the parent and pass it down to the child as a prop. A prop is a way to give data to another component. You can also give a function as a prop, so the child can use it to send data back to the parent. This lets the parent manage the state and the child show and change it.
For example:
const Child = ({ value, onChange }) => {
return (
<div>
<input value={value} onChange={onChange} />
</div>
);
};
const Parent = () => {
const [value, setValue] = useState("")
const handleChangeValue = (e) => {
setValue(e.target.value)
}
return (
<Child value={value} onChange={handleChangeValue} />
)
}
To learn more, please see sharing state between component.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论