javascript - 如何在 React 中定义 setFieldValue
问题描述
我正在使用 Formik 在创建实体之前验证字段。有一个 Select 打开一个下拉菜单,用户必须从那里选择一个选项。
我收到一条错误消息,说 setFieldValue 未定义,但在我没有找到此方法的任何定义之前我已经研究过,它就是这样使用的,所以我不知道为什么会发生这种情况。
这是我的代码:
import React from 'react';
import { Formik, Form, Field } from 'formik';
import { Button, Label, Grid } from 'semantic-ui-react';
import * as Yup from 'yup';
class CreateCompanyForm extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
industry: '',
};
}
onChange = (e, { name, value }) => {
this.setState({ [name]: value });
};
handleSubmit = values => {
// ...
};
render() {
const nameOptions = [
{ text: 'Services', value: 'Services' },
{ text: 'Retail', value: 'Retail' },
];
const initialValues = {
industry: '',
};
const requiredErrorMessage = 'This field is required';
const validationSchema = Yup.object({
industry: Yup.string().required(requiredErrorMessage),
});
return (
<div>
<div>
<Button type="submit" form="amazing">
Create company
</Button>
</div>
<Formik
htmlFor="amazing"
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={values => this.handleSubmit(values)}>
{({ errors, touched }) => (
<Form id="amazing">
<Grid>
<Grid.Column>
<Label>Industry</Label>
<Field
name="industry"
as={Select}
options={nameOptions}
placeholder="select an industry"
onChange={e => setFieldValue('industry', e.target.value)} // here it is
/>
<div>
{touched.industry && errors.industry
? errors.industry
: null}
</div>
</Grid.Column>
</Grid>
</Form>
)}
</Formik>
</div>
);
}
}
错误说:'setFieldValue' is not defined no-undef
- 它来自 ESLint。这怎么能解决?
解决方案
setFieldValue
可作为 Formik 中的道具之一访问。
我在CodeSandbox上尝试过,显然, onChange 道具中的第一个参数返回事件处理程序,而第二个参数返回选定的值 onChange={(e, selected) => setFieldValue("industry", selected.value) }
<Formik
htmlFor="amazing"
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={(values) => this.handleSubmit(values)}
>
{({ errors, touched, setFieldValue }) => (
//define setFieldValue
<Form id="amazing">
<Grid>
<Grid.Column>
<Label>Industry</Label>
<Field
id="industry" // remove onBlur warning
name="industry"
as={Select}
options={nameOptions}
placeholder="select an industry"
onChange={(e, selected) =>
setFieldValue("industry", selected.value)
}
/>
<div>
{touched.industry && errors.industry
? errors.industry
: null}
</div>
</Grid.Column>
</Grid>
</Form>
)}
</Formik>
推荐阅读
- flutter - 当父 BlocBuilder 重建时 Flutter 重建 BlocBuilder
- android - 如何在分页 3 库 android 的 PagingData 中添加多个项目?
- python - 如何通过调用其他函数的函数传递参数?
- c++ - How does sorting algorithms sort containers and ranges of floats?
- flutter - 在新选项卡中打开小部件时如何在 Flutter Web 中将数据作为查询传递?
- vue.js - vite 2 生产环境参考元素未使用 compostion api 定义
- .net - 测试入口点的 dotnet dll
- javascript - 将泛型表达式包装到函数中
- javascript - 如何生成一组地理空间坐标?
- python-3.x - Tkinter 程序的音频可视化器