首页 > 解决方案 > 如何在 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。这怎么能解决?

标签: javascriptreactjssemantic-uiformiksemantic-ui-react

解决方案


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>

推荐阅读