如何在react-select中使用字符串数组作为选项

时间:2019-02-04 11:27:23

标签: javascript reactjs redux react-redux react-select

我是react的新手。我正在使用react select进行选择。 现在,我有以下jsx

div className="col-md-4 d-flex align-items-center" style={borderClass}>
                <label className="mb-0 font-weight-bold" style={labelFont}>
                  Technology
                                </label>
                <Select
                  styles={styles}
                  options={this.props.technology}
                  placeholder="None Selected"
                />
              </div>


const mapStateToProps = (state) => {
  return {
    technology : state.CreateJob.technology,
    userCompany: state.CreateJob.userCompany
  }
}

这是来自减速器的道具。现在,我得到的数据就像,

['a', 'b', 'c']

因此,如何在渲染器中将此选项用作选项。谁能帮我这个 ?谢谢。

6 个答案:

答案 0 :(得分:2)

您可以呈现如下列表:

var array1 = ['a', 'b', 'c'];
var technologyList = [];
array1.forEach(function(element) {
    technologyList.push({ label:element, value: element })
});

并使用它:

<Select options={ technologyList } />

答案 1 :(得分:0)

您需要使用map遍历数组并为
渲染选项 渲染数组的每个部分。

<select className="form-control" value={currentValue} onChange={onChange}>
            <option value="">
                Select one...
            </option>
            {array.map(text,i => (
                <option key={i} value={text}>
                    {text}
                </option>
            ))}
        </select>

答案 2 :(得分:0)

将选择期望选项道具反应为具有属性值和标签的对象数组

 <Select
   styles={styles}
   options={this.props.technology.map(t=>({value: t, label: t}))}
   placeholder="None Selected"
 />

答案 3 :(得分:0)

您必须将字符串数组重新映射到对象数组,react-select接受此格式的选项prop。

[{ value: 'your value', label: 'your label' }]

<Select options={this.props.technology.map(t => ({ value: t, label: t})) } />

检出官方文档here

答案 4 :(得分:0)

React-Select期望使用以下格式的选项的对象数组:

[..., { value: 'optionValue', label: 'optionLabel' }, ...]

label属性显示给用户,并且值将在表单提交时发送到服务器。

因此,您需要根据从redux存储接收的数组创建给定格式的数组。

...
render(){
    const { technology } = this.props;
    const rsOptions = technology.map(x => {label: x, value: x});
    return (
        <div className="col-md-4 d-flex align-items-center" style={borderClass}>
            <label className="mb-0 font-weight-bold" style={labelFont}>Technology</label>
                <Select
                    styles={styles}
                    options={rsOptions}
                    defaultValue={{label: 'abcd', value: 'abcd'}}
                    // value={{label: 'abcd', value: 'abcd'}}  // use value instead of defaultValue if its an controlled input
                    // you can also use an object from your array by index
                    // defaultValue={rsOptions[0]}
                    // or you can use find in your array
                    // defaultValue={rsOptions.find(x => x.value === 'abcd)}
                    placeholder="None Selected"
                />
          </div>
    );
}
...

答案 5 :(得分:0)

<Select 
options={options} 
getOptionLabel={option => option} 
getOptionValue={option => option}
/>