我正在使用 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。这怎么能解决?
原文由 Leo Messi 发布,翻译遵循 CC BY-SA 4.0 许可协议
setFieldValue
可以作为 Formik 中的道具之一访问。我在 CodeSandbox 上尝试过,显然, onChange 道具中的第一个参数返回事件处理程序,而第二个参数返回选定的值 onChange={(e, selected) => setFieldValue(“industry”, selected.value) }