微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决Formik onChange 不适用于使用 react-select 的下拉列表

下面是我试图从下拉列表中选择值的代码handleChange 不起作用,当我从下拉列表中选择值时,它不会更新为从下拉列表中选择的值。它正在消失(空白)。

当我选择它没有捕捉到新的选定值时,下拉值会被填充。

有人可以帮我解决这个问题吗,就像我在这里缺少的一样?

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"                             
  />

解决方法

在使用 Formik 时应避免混合状态。 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?