gpt4 book ai didi

reactjs - 如何动态构建 Redux 表单?

转载 作者:行者123 更新时间:2023-12-03 14:04:20 26 4
gpt4 key购买 nike

我正在学习如何动态构建 redux-form。这个想法是,名为 componentDidMount 的组件从服务器获取项目列表并将它们插入到商店 store.my_items 中:

{'item1', 'itemB', 'itemZZZ', etc...} 

现在这些商品已在商店中,我想为 store.my_items 中的每个商品构建带有字段的 redux-form。

例如,其中几个是动态创建的:

      <div>
<label>ItemXXX</label>
<div>
<label>
<Field name="ItemXXX" component="input" type="radio" value="1" />
{' '}
1
</label>
<label>
<Field name="ItemXXX" component="input" type="radio" value="2" />
{' '}
2
</label>
</div>
</div>

使用 React、redux-form,构建这种类型的动态 Redux 表单的正确方法是什么?

最佳答案

我正在遵循这种动态构建表单的方法。我只是声明表单字段的元数据(类型、占位符、每个字段的唯一名称等),如下所示:

const fields = [
{ name: 'name', type: 'text', placeholder: 'Enter Name' },
{ name: 'age', type: 'number', placeholder: 'Enter age' },
{ name: 'email', type: 'email', placeholder: 'Enter Email' },
{ name: 'employed', type: 'checkbox' },
{
name: 'favouriteColors',
type: 'select',
options: [
{ label: 'Red', value: 'red' },
{ label: 'Yellow', value: 'yellow' },
{ label: 'Green', value: 'green' },
],
},
]

现在,我只是迭代这些字段并渲染每个字段的输入,就像我在下面给出的 renderField 组件中所做的那样。我的通用表单组件如下所示:

import React from 'react'
import { Field, reduxForm } from 'redux-form/immutable'

const renderField = ({ input, field }) => {
const { type, placeholder } = field
if (type === 'text' || type === 'email' || type === 'number' || type === 'checkbox') {
return <input {...input} placeholder={placeholder} type={type} />
} else if (type === 'select') {
const { options } = field
return (
<select name={field.name} onChange={input.onChange}>
{options.map((option, index) => {
return <option key={index} value={option.value}>{option.label}</option>
})}
</select>
)
} else {
return <div>Type not supported.</div>
}
}

const SimpleForm = ({ handleSubmit, fields }) => {
return (
<div>
{fields.map(field => (
<div key={field.name}>
<Field
name={field.name}
component={renderField}
field={field}
/>
</div>
))}
<div onClick={handleSubmit}>Submit</div>
</div>
)
}

export default reduxForm({
form: 'simpleForm'
})(SimpleForm)

并将字段传递给 SimpleForm 组件,如下所示:

<SimpleForm fields={fields} onSubmit={() =>{}}/>

现在您可以选择是要从服务器获取这样的字段,还是只想仅获取项目并在前端创建这样的字段(通过将项目作为字段名称传递)。

通过使用这种方法,我能够根据给定类型重用模板。

如果有人有更好的方法来动态制作表单,那么我也很想学习。

编辑:如果我们必须动态传递表单名称,则需要进行一些小更改:

export default reduxForm({})(SimpleForm)

我们可以在这个组件中传递表单名称,如下所示:

<SimpleForm form={'simpleForm'} fields={fields} onSubmit={() =>{}} />

关于reactjs - 如何动态构建 Redux 表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44480120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com