如何获得反应选择以与反应最终形式正确整合

时间:2019-09-24 18:58:29

标签: react-select react-final-form

我正在使用react-final-form来发送一些基本的用户数据。名字,姓氏,电子邮件和一个下拉列表,以及他们与我联系的原因。我尝试了以下操作(react-final-form的文档中的自定义输入部分):

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

我的猜测可能是与onChange道具发生冲突?不确定,但是下拉列表中的信息未被react-final-form收集并提交给<form>

2 个答案:

答案 0 :(得分:0)

有一个示例如何将react-selectreact-final-formhttps://codesandbox.io/s/40mr0v2r87一起使用。

您应该添加一个适配器:

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

然后您可以将其用作组件:

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

答案 1 :(得分:0)

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

<块引用>

{selectFieldId: "value"}

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;