如何动态编写 React.useState 函数,以便您可以从 cms 中获得任意数量的输入类型



这是一个假设的问题,因为我不确定我的方法是否可行。我在表单中有一堆输入复选框字段。我正在使用datoCms。我想我可以使用中继器模块来创建尽可能多的或删除复选框字段,并赋予它们与我在 dato 的文本字段中编写的相同的标签和名称作为中继器。现在拿督输出一个 graphQL api,我可以查询它,它会将中继器字段输出为一个数组,我可以在查询后映射它。

所以我会告诉你我的代码,以及我认为会起作用的东西,但我只需要指出正确的方向,我可以通过我的尝试来更新这个问题,但在这一点上我什至不知道从哪里开始。

让我感到困惑的部分是React.useState如何从映射方法动态地向其添加值。

好的,这是我的州代码

const [formState, setFormState] = React.useState({
name: "",
package: `${data.datoCmsPricing.title}`,
email: "",
subject: "",
weightLoss:"",
message: "",
})
const onChange = (e) => {
if (e.target.type === 'checkbox' && !e.target.checked) {
setFormState({...formState, [e.target.name]: ''});
} else {
setFormState({...formState, [e.target.name]: e.target.value });
}
}

这是我的表格

<form onSubmit={submitForm}>
<h3>Reasons for wanting to train</h3>
<label>
Weight Loss
<input 
type="checkbox"
name="weightLoss"
checked={formState.weightLoss}
onChange={onChange}
/>
</label>
<button type="submit">Submit</button>
</form>

现在这就是我建议我用表单来获取尽可能多的复选框的方法,这在这一点上基本上是 sudo 代码,因为我认为它会在checked部分中断

{data.datoCmsPricing.details.map(detailEntry => { 
return (

<label key={detailEntry.id}>
{detailEntry.reason}
<input 
type="checkbox"
name={detailEntry.reason}
checked={formState.{detailEntry.reason}}
onChange={onChange}
/>
</label>
)
})}

在此之后,我不知道我会如何处理状态?

提前谢谢你。链接到存储库 https://github.com/wispyco/jlfit

>useState非常适合动态数据。而且你的代码几乎是正确的。

  1. dataEntries属性添加到对象useState

    const [formState, setFormState] = React.useState({
    name: "",
    package: `package`,
    email: "",
    subject: "",
    weightLoss:"",
    message: "",
    dataEntries: { 
    '1': { reason: 'reason1', checked: false },
    '2': { reason: 'reason2', checked: false },
    '3': { reason: 'reason3', checked: false },
    '4': { reason: 'reason4', checked: false }, },
    })
    

    我已经用演示数据预填充了dataEtries。在实际应用程序中,这些数据将从后端获取。

  2. 修改onChange以正确处理dataEntries对象

    const onChange = e => {
    let value = undefined;
    if (e.target.type === "checkbox") value = e.target.checked;
    else value = e.target.value;
    setFormState({
    ...formState,
    dataEntries: {
    ...formState.dataEntries,
    [e.target.id]: {
    ...formState.dataEntries[e.target.id],
    [e.target.name]: value
    }
    }
    });
    };
    
  3. 最后在窗体控件上设置正确的nameid属性,以便onChange可以正确更新状态中的数据。

    export const Checkbox = ({ onChange, detailEntry }) => (
    <form>
    <label key={detailEntry.id}>
    {detailEntry.reason}
    <input
    type="checkbox"
    name="checked"
    id={detailEntry.id}
    checked={detailEntry.checked}
    onChange={onChange}
    />
    <input
    id={detailEntry.id}
    name="target weight"
    value={detailEntry["target weight"]}
    onChange={onChange}
    />
    </label>
    </form>
    );
    

    我添加了额外的字段"目标权重"来展示如何使用任何其他控件。

完整的演示在这里

最新更新