加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:41:05 所属栏目:百科 来源:网络整理
导读:我正在研究react-select库并面临一些问题,我正在使用redux-form库并导入 Field /来自它的组件.这样我就可以通过表单将值提交给服务了. 我的问题: 当我使用react-select的默认值时,下面提到的代码工作正常.我可以从下拉列表中选择值,即使在聚焦时也会选择该
我正在研究react-select库并面临一些问题,我正在使用redux-form库并导入< Field />来自它的组件.这样我就可以通过表单将值提交给服务了.

我的问题:

当我使用react-select的默认值时,下面提到的代码工作正常.我可以从下拉列表中选择值,即使在聚焦时也会选择该值,该值将保留.但是由于redux-form而选择的值不是通过表单提交的,这就是为什么我要包装组件并使用< Field name =“sample”component = {RenderSelectInput} id =“sampleEX”options = {options} />

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;

但是当我使用我的自定义选择(我正在包装以从表单提交值)时,< Select>即使值也可以在UI中看到组件.但是无法从下拉列表中选择值…,如果我选择它也会显示在< Select>中盒子,但在焦点上它消失了.请帮我 …

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;

谢谢,
词shash

当使用带反射形式的react-select时,你需要改变onChange和onBlur方法的默认行为,并分别调用redux-form的onChange和onBlur方法.

所以,试试这个:

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

并使用上面的组件

<Field component={RenderSelectInput} />

从Select字段中删除焦点时调用redux-form的onBlur方法可以防止丢失值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读