[英]Reactjs formik remove item from an array
I have these states in my component.我的组件中有这些状态。
const [initialValues, setInitialValues] = useState({
name: "",
name2: "",
items: []
});
name
and name2
combined together and made an array {name: 'sss', name2: 'sss'}
and push to the items
array. name
和name2
组合在一起形成一个数组{name: 'sss', name2: 'sss'}
并推送到items
数组。 The pushing part is okay.推送部分没问题。 The only problem is who to remove an item on that array.唯一的问题是由谁删除该数组上的项目。
This is my code https://codesandbox.io/s/material-demo-forked-u2qzv?file=/demo.js:260-362这是我的代码https://codesandbox.io/s/material-demo-forked-u2qzv?file=/demo.js:260-362
Normal array methods seem not to work here.普通数组方法在这里似乎不起作用。
How do I fix React and Formik?如何修复 React 和 Formik?
You could use Formik function setValues
to set form values您可以使用Formik函数setValues
来设置表单值
{
values.items.map((e, i) => (
<div key={e.i}>
<Button
variant='contained'
onClick={() => {
setValues({
name: '',
name2: '',
items: values.items.filter((newE) => newE !== e), // Remove clicked item
})
}}
>
remove {e.name}
</Button>
</div>
))
}
The full code snippet is below:完整的代码片段如下:
/* eslint-disable no-use-before-define */
import React, { useState } from 'react'
import { Button } from '@material-ui/core'
import { Formik, Form, Field } from 'formik'
import { TextField } from 'formik-material-ui'
export default function ComboBox() {
const [initialValues, setInitialValues] = useState({
name: '',
name2: '',
items: [],
})
return (
<Formik
initialValues={initialValues}
onSubmit={() => {}}
enableReinitialize
>
{({
isValid,
dirty,
values,
handleChange,
handleBlur,
setFieldValue,
setValues,
}) => {
return (
<Form>
<div>
<Field
name='name'
label='Name'
variant='outlined'
component={TextField}
variant='outlined'
fullWidth
/>
<Field
name='name2'
label='Name2'
variant='outlined'
component={TextField}
variant='outlined'
fullWidth
/>
</div>
<Button
variant='contained'
onClick={() => {
console.log('values', values)
setFieldValue(`items[${values.items.length}]`, {
name: values.name,
name2: values.name2,
})
}}
>
add item
</Button>
{values.items.map((e, i) => (
<div key={e.i}>
<Button
variant='contained'
onClick={() => {
setValues({
name: '',
name2: '',
items: values.items.filter((newE) => newE !== e), // Remove clicked item
})
}}
>
remove {e.name}
</Button>
</div>
))}
</Form>
)
}}
</Formik>
)
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const agents = [
{ name: 'Pathum', id: 1 },
{ name: 'Chamod', id: 2 },
{ name: 'Avishka', id: 3 },
]
I think the FieldArray
component is most appropriate to your use-case.我认为FieldArray
组件最适合您的用例。
I've modified your codesandbox example to use it:我已经修改了您的代码和框示例以使用它:
import React from "react";
import { Button } from "@material-ui/core";
import { Formik, Form, Field, FieldArray } from "formik";
import { TextField } from "formik-material-ui";
// Here is an example of a form with an editable list.
// Next to each input are buttons for insert and remove.
// If the list is empty, there is a button to add an item.
export default ComboBox = () => (
<Formik
initialValues={{
items: [
{
name: "James",
name2: "Bond"
}
]
}}
onSubmit={(values) =>
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
}, 500)
}
render={({ values }) => (
<Form>
<FieldArray
name="items"
render={(arrayHelpers) => (
<div>
{values.items && values.items.length > 0 ? (
values.items.map((item, index) => (
<div key={index}>
<Field
component={TextField}
variant="outlined"
fullWidth
label="Name"
name={`items.${index}.name`}
/>
<Field
component={TextField}
variant="outlined"
fullWidth
label="Name2"
name={`items.${index}.name2`}
/>
<Button
type="button"
onClick={() => arrayHelpers.remove(index)} // remove an item from the list
>
-
</Button>
<Button
type="button"
onClick={() =>
arrayHelpers.insert(index, { name: "", name2: "" })
} // insert an empty item at a position
>
+
</Button>
</div>
))
) : (
<Button
type="button"
onClick={() => arrayHelpers.push({ name: "", name2: "" })}
>
{/* show this when user has removed all items from the list */}
Add item
</Button>
)}
<div>
<Button type="submit">Submit</Button>
</div>
</div>
)}
/>
</Form>
)}
/>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.