React virtualized-select 自定义选项样式

React virtualized-select custom options styles

我正在使用虚拟化-select React 组件。我想在下拉菜单中设置选项的文本和背景颜色的样式。对于下面的简单代码,搜索栏背景为红色,当我 select 选项 1 时搜索栏背景变为蓝色,但我希望选项下拉列表中的背景为蓝色。此外,颜色属性似乎根本不起作用;只有某些 CSS 属性可以更改吗?

render () {

const styles = {
    color: "red",
    background: "red"
};

const options = [
  { label: "One", value: 1 , style: {background: 'blue'}},
  { label: "Two", value: 2 },
  { label: "Three", value: 3}
  //{ label: "Three", value: 3, disabled: true }
  // And so on...
]

return (
  <VirtualizedSelect
    options={options}
    onChange={(selectValue) => this.setState({ selectValue })}
    value={this.state.selectValue}
    placeholder="Search"
    style={styles}
  />
)
  }
}

react-virtualized-select 当前不支持 option.style 属性,如您在示例中所示,仅支持 option.className。 (可以看到default optionRender source here。)

如果您想要像您描述的那样自定义选项样式,则需要 override the optionRenderer as described in the docs. There's an example of this on the react-virtualized-select demo page (under "Custom Option Renderer") and the source code for that example is in the GitHub repo

我建议分叉默认渲染器并进行自定义,如下所示:

function YourOptionRenderer ({ focusedOption, focusOption, key, labelKey, option, selectValue, style, valueArray }) {
  const className = ['VirtualizedSelectOption']
  if (option === focusedOption) {
    className.push('VirtualizedSelectFocusedOption')
  }
  if (option.disabled) {
    className.push('VirtualizedSelectDisabledOption')
  }
  if (valueArray && valueArray.indexOf(option) >= 0) {
    className.push('VirtualizedSelectSelectedOption')
  }

  const events = option.disabled
    ? {}
    : {
      onClick: () => selectValue(option),
      onMouseEnter: () => focusOption(option)
    }

  return (
    <div
      className={className.join(' ')}
      key={key}
      style={{
        ...style,
        ...option.style,
      }}
      title={option.title}
      {...events}
    >
      {option[labelKey]}
    </div>
  )
}

或者,如果您想向项目提交 PR 以将对 option.style 的支持添加到默认渲染器 - 我愿意审核它。