简体   繁体   English

Formik onChange 不适用于使用 react-select 的下拉列表

[英]Formik onChange is not working for dropdown using react-select

Below is the code where I am trying to select value from dropdown.下面是我尝试从下拉列表中获取 select 值的代码。 handleChange is not working, when I select the value from dropdown it's not getting updated with selected value from dropdown. handleChange不起作用,当我 select 下拉列表中的值时,它不会使用下拉列表中的选定值进行更新。 It's getting vanished(blank).它正在消失(空白)。

Dropdown values are getting populated when I select it's not catching the new selected value.当我 select 它没有捕捉到新的选定值时,下拉值正在填充。

Can someone help me on this like what I am missing here?有人可以像我在这里缺少的那样帮助我吗?

export const FormikSelectField = ({ label, ...props }) => {
  const [field, meta] = useField(props);
  const [isFocused, setOnFocus] = useState(false);

  const handleChange = (value) => {
    // this is going to call setFieldValue and manually update values.topcis
    console.log('Value in handlechange..', value ,'and', props.name);
    props.onChange(props.name, value.value);
  };

  const handleFocus = () => {
    setOnFocus(true);
  };
  const handleBlur = (e) => {
    // this is going to call setFieldTouched and manually update touched.topcis
    setOnFocus(false);
    props.onBlur(props.name, true);
    field.onBlur(e);
  };
  return (
    <>
      <label htmlFor={props.labelName}>{props.labelName} </label>
      <Select
        id={props.labelName}
        options={props.options}
        isMulti={false}
        onChange={handleChange}
        onBlur={(e) => handleBlur(e)}
        placeholder='Select an option'
        onFocus={handleFocus}
        value={props.value}
      />
      {meta.touched && meta.error && !isFocused ? (
        <div className="error">{meta.error}</div>
      ) : null}
    </>
  );
};
 formikInitialValues = () => {
         return {
         Name: [{
                title: '',
                value: '',
              }]
         };         
    };

   YupValidationSchema = () => {
        return Yup.object({
    Name: Yup.array()
            .of(
              Yup.object().shape({
                title: Yup.string().required(),
                value: Yup.string().required(),
              })
            )
            .required("Please select an option")
            .nullable()

        });
      };
<FormikSelectField 
        value={this.state.selectNameOption}
        onChange={this.handleNameChange}
        onBlur={this.handleNameChangeBlur}
        error={formik.errors.Name}
        options={this.state.NameOptions}
        touched={formik.touched.Name}
        name="Name"
        labelName="Name"                             
  />

You should avoid mixing the state when using Formik.使用 Formik 时应避免混合状态。 Formik will take care of the state for you. Formik 会为您处理好状态。

import { Formik, Form, useField, ErrorMessage } from "formik";
import * as Yup from "yup";
import Select from "react-select";

const iceCreamOptions = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" },
  { value: "vanilla", label: "Vanilla" }
];

const FormSelect = ({ name, options }) => {
  const [field, meta, helpers] = useField(name);
  return (
    <>
      <Select
        name={name}
        value={field.value}
        onChange={(value) => helpers.setValue(value)}
        options={options}
        onBlur={() => helpers.setTouched(true)}
      />
      <ErrorMessage name={name} />
    </>
  );
};

const initialValues = {
  icecream: null
};

const validationSchema = Yup.object().shape({
  icecream: Yup.object()
    .shape({
      value: Yup.string(),
      label: Yup.string()
    })
    .required("Please select a value")
    .nullable()
});

export default function App() {
  return (
    <Formik
      initialValues={initialValues}
      onSubmit={(values) => console.log(values)}
      validationSchema={validationSchema}
    >
      {(props) => {
        return (
          <Form>
            <pre>{JSON.stringify(props, undefined, 2)}</pre>
            <FormSelect name="icecream" options={iceCreamOptions} />
          </Form>
        );
      }}
    </Formik>
  );
}

Example Working Sandbox 示例工作沙箱

Write this code写这段代码

onChange={(e:React.ChangeEvent<HTMLInputElement>)=> setFieldValue("title",e.target.value)}

or或者

onChange={(e)=> setFieldValue("title",e.target.value)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM