【问题标题】:Multi select from react-select with redux-form not working as intended来自 react-select 的多选与 redux-form 未按预期工作
【发布时间】:2017-04-26 09:39:05
【问题描述】:

所以我使用来自 react-select 的多选和 redux-form 以及 onBlur hack(?) 这在幕后工作正常,因为当我提交它时,我在值中有选定的数据

但是在访问任何多选字段后(即使我没有选择任何内容)我最终没有任何值(除了这个
))

const options = [
    { value: 'one', label: 'One' },
    { value: 'two', label: 'Two' }
];

<Select
            value="one"
            options={options}
            multi={true}
            {...input}
            onBlur={() => {
              input.onBlur({...input.value})
            }
          }
        />

所以我最终得到了 redux 状态的值,但我在该字段中看不到任何值。有人知道为什么会这样吗?

【问题讨论】:

    标签: reactjs redux redux-form react-select


    【解决方案1】:

    以下是如何使其工作的示例。 react-select (1.0.0-rc.2), redux-form (5.3.4)

    SelectInput.js

    import React from 'react';
    import Select from 'react-select';
    import 'react-select/dist/react-select.css';
    
    export default (props) => (
      <Select
        {...props}
        value={props.input.value}
        onChange={(value) => props.input.onChange(value)}
        onBlur={() => props.input.onBlur(props.input.value)}
        options={props.options}
      />
    );
    

    MyAwesomeComponent.js

    import React, {PureComponent} from 'react';
    import SelectInput from './SelectInput.js';
    
    class MyAwesomeComponent extends PureComponent {
      render() {
        const options = [
          {'label': 'Germany', 'value': 'DE'},
          {'label': 'Russian Federation', 'value': 'RU'},
          {'label': 'United States', 'value': 'US'}
        ];
      return (
        <Field
          name='countries'
          options={options}
          component={SelectInput}
          multi
        />
      )
    };
    

    【讨论】:

    • 这适用于多选和非多选。
    • 最佳答案!救我一天!
    【解决方案2】:

    我没有使用更现代的react-select 版本,但一年前,有一些问题是必须通过delimiter 将字符串值split() 以将值作为数组获取,然后@987654324再次@他们给组件。

    像这样的东西:

    if (multi) {
      selectValue = value ? value.join(delimiter) : ''
    } else {
      selectValue = value || null
    }
    

    我建议使用 Redux DevTools 准确检查 Redux 中的值,以及传递给 react-select 的值属性。我相信你会在那里找到问题。

    【讨论】:

    • 感谢您的回复埃里克。在发布这个问题后我确实做到了,结果我必须在 onBlur 函数中传递选定值的数组而不是对象,所以这样做input.onBlur([...input.value]) 解决了这个问题。话虽如此,您是否建议使用除了 react-select 之外的其他东西?使用 redux-form 也让我很难控制表单输入的状态。你会推荐给刚接触 redux 的人吗?
    • PS 我知道 redux-form 是你的仓库,所以我希望你没有偏见(呵呵)
    • 嘿。还有另一个名为react-redux-form 的库可能更适合您的思维方式。不,我真的没有比 react-select 更好的选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2020-08-19
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    相关资源
    最近更新 更多