【发布时间】:2020-11-17 09:01:33
【问题描述】:
这是一个棘手的问题。假设我有一个组件<GrandFather />,里面有一个<Form /> 组件。 <Form /> 有多个 <Input /> 组件。 <Input /> 有一个内部 useState。在<GrandFather />,有一些函数,比如loadForm(加载一些字段)和unloadForm(删除这些字段)。在 unloadForm 上,我想重置输入的内部状态。我发现的唯一解决方案是在<Form /> 上有一个键并在卸载时增加它,这样就可以强制其余的。有没有更好的方法在不改变逻辑的情况下做到这一点? P.S 我正在使用 Typescript。
function GrandFather (props: Props) {
const loadForm = () => // load some fields to the formData
const unloadForm = () => // unload these fields to the formData
return <Form formData={formData}/>
}
function Form (formData: FormData) {
return (
<>
<Input /> // with some props
<Input /> // with some props
<Input /> // with some props
</>
)
}
function Input (props: Props) {
const [state, setState] = useState(false);
// the state here is being used for styling and animations, at
// somepoint it will became true
return <TextInput {...props}/>
}
这里有什么方法可以将此状态重置为函数 unloadForm 上的所有输入?
【问题讨论】:
-
可以分享一下代码吗?
标签: reactjs react-hooks state native