我有一个表单:
<FieldLabel label='Label'>
<Textfield
value={formState.name}
onChange={name => setFormState({ ...formState, name })}
name="someName"/>
</FieldLabel>
<FieldLabel label='Description'>
<Textarea
value={formState.description}
onChange={description => setFormState({ ...formState, description}}
name="someDesc"/>
</FieldLabel>
此表单是"dumb",这意味着它从父级获取其formState,并在输入更改时分派setFormState。在父组件中,它看起来像:
<MyForm
formState={formState}
setFormState={setFormState} />
其中formState和setFormState是挂钩:
const initialFormState: FormState = {
name: '',
description: '',
}
const [formState, setFormState] = useState<FormState>({ ...initialFormState });
然而,状态不会改变,我也无法在表单上的输入中写入任何内容。当我单击提交时,初始状态被记录下来,所有属性都是空字符串,就像initialFormState中一样。
如果有人需要更多信息,我很乐意提供。谢谢。
添加代码沙盒链接:https://codesandbox.io/s/admiring-haze-gsy59?file=/src/App.js
onChange在输入时不发出值,而是发出事件。
更换为onChange={e => setFormState({ ...formState, name: e.target.value })}