【问题标题】:How can I get react-select to integrate properly with react-final-form如何让 react-select 与 react-final-form 正确集成
【发布时间】:2020-01-24 22:50:41
【问题描述】:

我正在使用react-final-form 发送一些基本的用户数据。名字、姓氏、电子邮件和下拉值,以及他们联系我的原因。我尝试了以下方法(react-final-form's docs 上的自定义输入部分):

<Field name="myField">
  {props => (
    <div>
      <Select
        options={colourOptions}
        className="basic-multi-select"
        classNamePrefix="select"
        onChange={props.input.onChange}
       />
    </div>
  )}
</Field>

我的猜测是可能与 onChange 道具发生了冲突?不确定,但react-final-form 没有获取下拉列表中的信息,并在提交时传递给&lt;form&gt;

【问题讨论】:

    标签: react-select react-final-form


    【解决方案1】:

    以一种简单的方式,我这样做了:

     const locationOptions = [
            { value: 1, label: "ADEN" },
            { value: 2, label: "MUKALLA" },
            { value: 3, label: "TAIZ" },
          ];
    <Field name="location_id">
                  {({ input }) => (
                    <Select
                      options={locationOptions}
                      placeholder="Select Location"
                      {...input}
                    />
                  )}
    </Field>
    

    on submit 方法:

    const onSubmit = (data) => {
        console.log(data);
      };
    

    【讨论】:

      【解决方案2】:

      这是我的方法。我决定了将发送到服务器的初始值和值的问题。就像:

      {selectFieldId: "值"}

      import React from "react";
      import { FieldRenderProps } from "react-final-form";
      import Select, { ValueType } from "react-select";
      
      type Option = {
          label: string;
          value: string;
      };
      
      export const CustomSelect = ({ input, options, ...rest }: FieldRenderProps<string, HTMLElement>) => {
      
          const handleChange = (option: ValueType<Option, false>) => {
              input.onChange(option?.value);
          };
      
          return (
                  <Select
                      {...input}
                      {...rest}
                      onChange={handleChange}
                      options={options}
                      value={options ? options.find((option: Option) => option.value === input.value) : ""}
                  />
          );
      };
      
      export default CustomSelect;
      

      【讨论】:

        【解决方案3】:

        有一个关于如何使用react-selectreact-final-form 的示例:https://codesandbox.io/s/40mr0v2r87

        你应该添加一个适配器:

        const ReactSelectAdapter = ({ input, ...rest }) => (
          <Select {...input} {...rest} />
        )
        

        然后你就可以把它当成一个组件来使用了:

        <Field
          name="state"
          component={ReactSelectAdapter}
          options={states}
        />
        

        【讨论】:

          猜你喜欢
          • 2021-05-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多