在我正在开发的应用程序中,有一个模块可以进行调查/投票。后端已经编程,基本上有一个端点在主体中接受一个复杂的对象,然后它将构建轮询。复杂对象可以根据投票和问题类型而有所不同,有的是选择题,有的是投票,有的是开放式的。这个复杂对象的一个例子,我正在尝试像这样构建厕所:
{
"title": "Newish first poll",
"description": "juan's first wizard poll",
"status": "new",
"start_date": "2019-03-12 08:00:00",
"end_date": "2019-03-25 08:00:00",
"questions" : [
{
"question_text":"HOW CAN DIS BE",
"type":"1",
"choices": []
},
{
"question_text":"Choose your weapon",
"type":"0",
"choices": [
{
"choice_text": "Sword",
"description": "Sharp and durable, the sword is very popular."
},
{
"choice_text": "Hammer",
"description": "Stop!"
},
{
"choice_text": "Poetry",
"description": "Nothing more devastating than a poetry slam"
}
]
},
{
"question_text":"Do you agree?",
"type":"1"
}
]
}
从本质上讲,该对象具有名为问题的字段数组,其中包含问题对象。但是,如果是多项选择题,这些问题对象也可以包含选项数组,并且每个选项都有 2 个潜在字段,选项文本和选项描述。
一般而言,仅使用 onefield 数组和可用的 mutator push,我就能够推送一个完整的问题对象,目前已硬编码到一个变量中,如下所示:push('questions',sampleQuestion1)
按下按钮时。
由于问题数组已经包含 choices[] 数组,那么表单将起作用,但是,我无法像在 FieldArray 的顶层中那样呈现 choices 数组的值在 other 中
这是基本实现的样子
<FieldArray name='questions'>
{({fields})=>(
<div>
{fields.map((question,i)=>(
<div key={i}>
<div className={'form-group'}>
<InputField name={`${question}.question_text`} placeholder={'Pregunta'} disabled/>
<FieldArray name={'choices'}>
{({fields})=>(
//i would like to be able to map through fields of the choices array, if present
)}
</FieldArray>
</div>
</div>
))}
</div>
)}
</FieldArray>
我尝试在另一个字段数组中放入一个组件,这当然是相当幼稚的,我很快发现推送突变器已经用添加的数据调用,而且我无法通过选择字段进行映射,因为问题在父 fields.map
中传递的对象本身并不是问题对象。
我尝试了一些其他技术并阅读了文档,但我有点难过。如果有人能帮我弄清楚这是否可行,我将非常感激
最佳答案
我认为您不了解 FieldArray
的用途。 FieldArray
适用于当您的数据(表单提交的内容)包含一个数组时其长度可以由用户更改。您拥有的是一系列要呈现到字段中的问题。您应该只映射它们并渲染字段。
像这样:
<form>
{questions.map((question, index) => (
<label>{question.question_text}</label>
{question.type === 1 && <Field name={`answers[${index}]`} component="input" type="checkbox"/>}
{question.type === 0 && <Field name={`answers[${index}]`} component="select">
{question.choices.map(choice => <option>{choice.choice_text}</option>}
</Field>}
))}
</form>
我不能保证编译成功,但它应该给你一个大概的想法。它将生成表单数据,在提交时,该数据包含一个 answers
数组,其索引与 questions
数组匹配。
这有帮助吗?
关于javascript - 如何使用 React-final-form 将 FieldArray 功能嵌套在其他 <FieldArray> 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56744334/