React 中使用 formik 的字段数组
我想像待办事项列表一样关注。就像下面的图片一样。 现在,我的代码的问题是,它的工作方式不同。 我只想要一个呈现 div 列表而不是输入字段的输入。 如下图所示:
请在此处检查我的代码和框
<FieldArray
name="todos"
render={(arrayHelpers) => (
<div>
{formik.values.todos.map((friend, index) => (
<div key={index} style={{ display: "flex", gap: "1rem" }}>
<input
name={`todos[${index}].name`}
value={formik.values.todos[index].name}
onChange={formik.handleChange}
/>
<button
disabled={formik.values.todos?.length === 1}
type="button"
onClick={() => arrayHelpers.remove(index)}
className="deleteButton"
>
Remove
</button>
</div>
))}
<button
type="button"
onClick={() => arrayHelpers.push({ name: "" })}
>
Add
</button>
</div>
)}
/>
I wanted to follow like a todo list. Something just like in the picture below.
Right now, the problem with my code is that, its working differently.
I wanted only one input that renders a list of divs instead of input fields.
Exactly just like in the picture below:
Pls check my codesandbox here
<FieldArray
name="todos"
render={(arrayHelpers) => (
<div>
{formik.values.todos.map((friend, index) => (
<div key={index} style={{ display: "flex", gap: "1rem" }}>
<input
name={`todos[${index}].name`}
value={formik.values.todos[index].name}
onChange={formik.handleChange}
/>
<button
disabled={formik.values.todos?.length === 1}
type="button"
onClick={() => arrayHelpers.remove(index)}
className="deleteButton"
>
Remove
</button>
</div>
))}
<button
type="button"
onClick={() => arrayHelpers.push({ name: "" })}
>
Add
</button>
</div>
)}
/>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个非常简单粗暴的方法 - 我在我的项目中使用了 Formik前一段时间,我很确定它并不完美,但这正是您所需要的。
所以一些细节。
todos< 中的
name
字段/代码>。单击添加
按钮时状态将被清除。formik.values.todos.lenght > 时才需要渲染元素0
formik.values.todos.lenght === 1
时,您需要禁用Delete
按钮Add
按钮newValue.lenght === 0
小菜一碟,对吧?
Here is a very simple and rude approach - I used Formik my project some time ago and I'm pretty sure it's not perfect but this is exactly what you need.
So some details.
name
field in yourtodos
. State is cleaned when you clickAdd
button.formik.values.todos.lenght > 0
Delete
button whenformik.values.todos.lenght === 1
Add
button should be disabled whennewValue.lenght === 0
Piece a cake, right?