【发布时间】:2022-02-14 16:36:24
【问题描述】:
我正在学习 ReactJS 并使用 Formik 库进行用户输入。
我一直在尝试设计一个表,其第一行(标题)包含显示的每个列的输入字段,但我似乎无法找到将所述字段分布在它们自己的列上的方法。他们都挤在表格的第一列。
<table>
<thead>
<tr>
<th scope="col">
{/* TODO: Fix this form as it currently loads into a single column */}
<Formik
initialValues={hobbyInitialValues}
onSubmit={SubmitHobby}
validationSchema={ValidateHobby}
>
<Form>
<Field className="selectField" as="select" name="passion">
<option value="" label="Select Passion" />
<option value="Low" label="Low" />
<option value="Medium" label="Medium" />
<option value="High" label="High" />
</Field>
<Field
className="inputField"
id="inputHobbyName"
name="name"
placeholder="Enter User Hobby"
/>
<Field
className="inputField"
id="inputYear"
name="year"
placeholder="Enter Year"
/>
<button className="submitButton" type="submit">
Add
</button>
</Form>
</Formik>
</th>
</tr>
</thead>
<tbody>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</tbody>
</table>
尝试将单个字段包含在一个字段中会导致此错误,因为 Formik 和 React Tables 都限制了组件可以拥有的子项:
Warning: validateDOMNesting(...): <form> cannot appear as a child of <tr>.
我怎样才能达到预期的效果?
编辑:感谢 Wraithy 的回答,我的问题得到了解决。代码如下:
<Formik
initialValues={hobbyInitialValues}
onSubmit={SubmitHobby}
validationSchema={ValidateHobby}
>
<Form>
<table>
<thead>
<tr>
<th scope="col">
<Field className="selectField" as="select" name="passion">
<option value="" label="Select Passion" />
<option value="Low" label="Low" />
<option value="Medium" label="Medium" />
<option value="High" label="High" />
</Field>
</th>
<th scope="col">
<Field
className="inputField"
id="inputHobbyName"
name="name"
placeholder="Enter User Hobby"
/>
</th>
<th scope="col">
<Field
className="inputField"
id="inputYear"
name="year"
placeholder="Enter Year"
/>
</th>
<th scope="col">
<button className="submitButton" type="submit">
Add
</button>
</th>
</tr>
</thead>
<tbody>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</tbody>
</table>
</Form>
</Formik>
【问题讨论】: