首页 > 解决方案 > 如何将数组传递给 ReactSelect

问题描述

我有一个名为times的字符串数组。其格式如下: 在此处输入图像描述

我将它作为道具传递给了一个组件,但我很难将它传递给 ReactSelect 组件。

const TimeInput=(
            <div>
                <ReactSelect
                        className='react-select react-select-top'
                        classNamePrefix='react-select'
                        id='displayLanguage'
                        menuIsOpen={this.state.openMenu}
                        menuPortalTarget={document.body}
                        styles={reactStyles}
                        **options={this.props.times}**
                        clearable={false}
                        onKeyDown={this.handleKeyDown}
                        onMenuClose={this.handleMenuClose}
                        onMenuOpen={this.handleMenuOpen}
                        aria-labelledby='changeInterfaceLanguageLabel'
                    />
            </div>
        )

当我尝试将时间数组传递给 ReactSelect 时出现此错误(请忽略之后的错误,因为这些是我尚未处理的函数,即。handleMenuClose:

在此处输入图像描述

标签: reactjs

解决方案


optionsprop 接收带有键的 JSON 对象数组和valuelabel因此您需要将时间数组转换为该格式。

一种方法是映射

// Before your render function

const timeOptions = this.props.times.map((timeString) => {
  // Ideally you can change the value to something different that is easier to keep track of like the UTC offset
  return {
      value: timeString,
      label: timeString
    }
  }
);

// In render function
// Now pass in timeOptions as the prop for your ReactSelect
...
<ReactSelect
...
  options={timeOptions}
...>


推荐阅读