如何使用字符串数组作为反应,选择一个选项

问题描述 投票:0回答:5

我是新来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']

所以,我怎样可以用这个作为渲染选项。谁能帮我这个 ?谢谢。

javascript reactjs redux react-redux react-select
5个回答
2
投票

可以渲染像这样的列表:

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

并使用它:

<Select options={ technologyList } />

0
投票

你需要使用地图遍历数组并呈现一个选项 呈现每个片阵列的。

<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>

0
投票

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

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

0
投票

您必须在字符串数组重新映射到对象的数组,反应,选择接受这种格式选项支撑。

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

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

结帐官方文档here


0
投票

反应 - 选择希望与此格式选项对象的数组:

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

标签属性被显示给用户,和值将被发送到服务器上提交表单。

你,所以你需要在给定的格式创建一个数组从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>
    );
}
...
© www.soinside.com 2019 - 2024. All rights reserved.