我正在构建一个表单,其中所有输入,标签和简短描述都是根据数据库中的数据创建的。例如:
settings = [
{
name: Setting_Name_Enabled,
groupType: "setting1",
labelText: "Setting Name Enabled",
description: "This setting enables something",
inputType: "checkbox",
value: "True"
},
{
name: Setting_Name_Days,
groupType: "setting1",
labelText: "Setting Name In Days",
description: "This setting will be triggered every N days",
inputType: "number",
value: "15"
}
我想基于这些记录及其属性动态地构建表单。我有以下内容,但由于set.inputType和setting.labelText似乎没有被拾取而无法正常工作。如果我将输入类型硬编码为文本,则所有内容都会显示出来,而不是标签或试图随对象访问属性的任何地方。
const renderField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<label>{label}</label>
<div>
<input {...input} type={type} />
{touched && error && <span>{error}</span>}
</div>
</div>
);
const renderSettings = ({ fields, meta: { touched, error, submitFailed } }) => (
<div>
{fields.map((setting, index) => (
<Field
name={`${setting}.value`}
type={ setting.inputType }
component={renderField}
label={ setting.labelText }
/>
))}
</div>
);
答案 0 :(得分:0)
代码问题是setting
中的fields.map
对象无法从settings数组访问该对象的属性。
您可以使用Redux表单的fields.get(index)函数来获取值。
最终代码如下:-
const renderField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<label>{label}</label>
<div>
<input {...input} type={type} />
{touched && error && <span>{error}</span>}
</div>
</div>
);
const renderSettings = ({ fields, meta: { touched, error, submitFailed } }) => (
<div>
{fields.map((setting, index) => (
<Field
name={`${setting}.value`}
type={fields.get(index).inputType}
component={renderField}
label={fields.get(index).labelText}
/>
))}
</div>
);