【发布时间】:2021-06-20 07:52:59
【问题描述】:
我在尝试在数组中存储数据时遇到了一些问题。
我创建了一个我多次使用的组件输入。每个输入存储关于用户的不同数据。我想格式化一个对象,其中所有这些信息都将以 json 类型存储。为此,我使用反应 context。但问题是,每次我在我的字段中写入数据时,前一个都会被删除。我知道如何在前一个状态之后在数组中插入,但对于对象,...prevState 不起作用。
此外,如何在 json 中使用我作为道具传递的标签?因为我把label 认为它实际上会获取道具值,但它没有,它只是用label 填充数据。
这是组件
type Label = {
label: string
type: string
}
export const Forms = ({ label, type }: Label) => {
const {userData, setUserData} = useContext(RegisterContext)
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
e.preventDefault()
// setUserData(prev => [prev, e.target.value]) this is what I used to do with array
setUserData({type: e.target.value})
}
return (
<div className="flex flex-col w-64">
<span className="text-appiness-darkblue">{label}</span>
<input onChange={handleChange} type={type} className="rounded-md bg-appiness-green focus:outline-none focus:ring focus:border-appiness-darkblue"/>
</div>
)
}
这就是我的称呼
<div className="grid grid-cols-2 justify-items-center w-5/12">
<Forms type="text" label="Username"/>
<Forms type="string" label="First name"/>
<Forms type="string" label="Last name"/>
<Forms type="string" label="Email"/>
<Forms type="password" label="Password"/>
<Forms type="date" label="Date of Birth"/>
</div>
【问题讨论】:
-
setUserData(prev => { ...prev, type: e.target.value })? -
@raina77ow 我已经尝试过了,我在
...prev上收到了a spread argument must either have a tuple type or be passed to a rest parameter
标签: reactjs typescript use-context