ReactJS:如何在redux-form字段中包含react-select?

sha*_*ash 14 reactjs react-bootstrap react-select redux redux-form

我正在研究react-select图书馆并面临一些问题,我正在使用redux-form库并<Field />从中导入组件.这样我就可以通过表单将值提交给服务了.

我的问题:

当我使用react-select的默认值时,下面提到的代码工作正常.我可以从下拉列表中选择值,即使在聚焦时也会选择该值,该值将保留.但选择的值不是通过表单提交,因为<Select>这就是我包装组件和使用的原因redux-form

import React from 'react';
import Select from 'react-select';
import RenderSelectInput from './RenderSelectInput'; // my customize select box

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


class SelectEx extends React.Component {
    constructor() {
        super();
        this.state = { selectValue: 'sample' }
        this.updateValue = this.updateValue.bind(this);
    }

    updateValue(newValue) {
        this.setState({ selectValue: newValue })
    }

    render() {

        return (
            <div>
                <Select name="select1" id="selectBox" value={this.state.selectValue} options={options} onChange={this.updateValue}/>

                //This works but value won't submit ...

                <Field name="sample" component={RenderSelectInput} id="sampleEX" options={options} />
            //For this, selected value vanishes once I come out of component. 
            </div>
        )
    }
}

export default SelectEx;
Run Code Online (Sandbox Code Playgroud)

但是当我使用我的自定义选择(我正在包装以从表单提交值)时,<Select />组件也可以在UI中显示,即使值也是如此.但无法从下拉列表中选择值...,如果我选择它也会显示在<Field name="sample" component={RenderSelectInput} id="sampleEX" options={options} />框中,但在焦点上它会消失.请帮我 ...

RenderSelectInput组件:

import React from 'react';
import {Field, reduxForm} from 'redux-form';
import Select from 'react-select';
import 'react-select/dist/react-select.css';


const RenderSelectInput = ({input, options, name, id}) => (

    <div>
        <Select {...input} name={name} options={options} id={id} />
    </div>
)

export default RenderSelectInput;
Run Code Online (Sandbox Code Playgroud)

谢谢,Shash

Har*_*dha 10

使用react-selectredux-form时,您需要分别更改onChangeonBlur方法的默认行为,并分别调用redux-form's onChangeonBlur方法' .

所以,试试这个:

const RenderSelectInput = ({input, options, name, id}) => (
    <Select 
         {...input}
         id={id} 
         name={name} 
         options={options}
         value={input.value}
         onChange={(value) => input.onChange(value)}
         onBlur={(value) => input.onBlur(value)}
    />
)
Run Code Online (Sandbox Code Playgroud)

并使用上面的组件

<Field component={RenderSelectInput} />
Run Code Online (Sandbox Code Playgroud)

呼叫redux-formonBlur当焦点被从除去方法Select字段将防止价值损失.

  • 可能有点晚了,但我现在面临同样的问题并解决了它调用`input.onBlur`而没有参数:`onBlur = {()=> input.onBlur()}`.显然,`Select`的`onBlur`方法接收一个事件,`input.value`是一个空字符串,调用`input.onBlur`,其中任何一个值都用`payload =''`调度BLUR动作. redux状态中字段的值 (7认同)