我知道这个问题似乎很基本,但是我正在学习React和Formik。我正在尝试构建一个表单组件,用户可以在其中根据需要动态添加新输入。这存储在“名称”组件中,该组件将导入“调查”组件中。
似乎Names组件没有从initialValues获取值,因为这是我得到的错误。
./src/components/Names.js
Line 20:12: 'values' is not defined no-undef
Search for the keywords to learn more about each error.
我试图将它们作为道具传递下来,但似乎并没有意识到。
“调查”组件如下所示
import React, { Component } from 'react';
import { Formik, Field, Form, ErrorMessage, FieldArray } from 'formik';
import * as Yup from 'yup';
import Names from './Names'
const Survey = () => {
return (
<Formik
initialValues={{
names: [{firstName: '', lastName: '', middleName: '', id: "" + Math.random()}]
}}
validationSchema={Yup.object({
firstName: Yup.string()
.max(15, 'Must be 15 characters or less'),
lastName: Yup.string()
.max(20, 'Must be 20 characters or less')
})}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
}, 500)
}}
>
{({ values, errors, isSubmitting }) => (
<Form>
<Names values={values}/>
<button type="submit">Submit</button>
</Form>
)}
</Formik>
)
}
export default Survey;
这里是名称组件
import React, { Component } from 'react';
import { Formik, Form, useField, FieldArray } from 'formik';
import * as Yup from 'yup';
import InputField from './InputField'
const Names = (props) => {
return (
<>
<FieldArray name="names">
{(arrayHelpers) => (
<div>
<button onClick={() =>
arrayHelpers.push({
firstName: '',
middleName: '',
lastName: '',
id: "" + Math.random()
})
}>Add a Name</button>
//NOT BEING RECOGNIZED
{values.names.map((name, index) => {
return (
<div key={name.id}>
<InputField
label="First Name"
name={`names.${index}.firstName`}
type="text"
placeholder="Enter Your First name"/>
<InputField
label="Middle Name"
name={`names.${index}.middleName`}
type="text"
placeholder="Enter Your Middle name"/>
<InputField
label="Last Name"
name={`names.${index}.lastName`}
type="text"
placeholder="Enter Your Last name"/>
<button onClick={() => arrayHelpers.remove(index)}>Remove name</button>
</div>
);
})}
</div>
)}
</FieldArray>
</>
);
};
export default Names;
我也尝试过将其传递为
values.names
从Survey组件中,然后在我写的Name组件中
this.props.values.map
但这也不起作用。
任何帮助将不胜感激。预先感谢!
答案 0 :(得分:0)
好的,我找到了答案。
它必须是
props.values.map
因为我将其作为“道具”传递了下来。这就是为什么仅“值”不起作用的原因。