简体   繁体   English

使用 Formik 使用 react-select 时设置初始 state 值

[英]Setting initial state values when using react-select with Formik

I am trying to use react-select (with multi-values) with Formik but unsure how to reflect values selected within my Formiks initialStates values.我正在尝试将 react-select(具有多值)与 Formik 一起使用,但不确定如何反映在我的 Formiks initialStates 值中选择的值。

I have the following:我有以下内容:

import Select from 'react-select';

const myOptions= [
  { value: 'Food', label: 'Food' },
  { value: 'Being Fabulous', label: 'Being Fabulous' },
  { value: 'Unicorns', label: 'Unicorns' },
  { value: 'Kittens', label: 'Kittens' },
];


"props": {
    "myGroups": [
        {
            "myGroupName": "",
            "selectedOptions": []
        }
     ]
 }


<Select
   options={myOptions}
   isMulti={true}
   name={`myGroups.${index}.selectedOptions`}
/>

I am able to populate the react-select list correctly but unsure what I need to do with setting: myGroups.${index}.selectedOptions to hold the values like:我能够正确填充 react-select 列表,但不确定我需要如何设置: myGroups.${index}.selectedOptions来保存如下值:

"selectedOptions": [
                    "Food",
                    "Kittens"
                   ]

I'm assuming I will need an onChange function call and with Formik, will also need to use setFieldValue我假设我需要一个onChange function 调用,并且使用 Formik,还需要使用setFieldValue

Any help would be great.任何帮助都会很棒。

I have previously worked on this library and required to do the exact same thing as you do.我以前在这个库上工作过,需要做和你一样的事情。

Just add an onChange event.只需添加一个onChange事件。 Then, have a variable e that will match with handleChange event from Formik .然后,有一个变量e将与来自FormikhandleChange事件匹配。

<Formik initialValues={initialFormValues} validationSchema={formSchema} onSubmit={this.handleFormSubmit} enableReinitialize>
    {({ handleSubmit, handleChange }) => (
        <Form noValidate onSubmit={handleSubmit} autoComplete='off'>
            <Select
                options={myOptions}
                isMulti={true}
                name={`myGroups.${index}.selectedOptions`}
                onChange={(selectedOption) => {
                    let e = { target: { name: `myGroups.${index}.selectedOptions`, value: selectedOption } };
                    handleChange(e);
                }}
            />
        </Form>
    )}
</Formik>

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

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