使用自定义组件时如何在 React-Select 中设置所选项目的样式?

How to style the selected item in React-Select when using a custom component?

我们正在使用自定义的 Emotion 组件,文档中说相同的属性会传递给客户组件,但它们似乎并非如此。 isSelected 其他属性似乎也不存在。

const Option = styled.div`
  color: #444;
  font-family: 'Open Sans', 'Arial', Sans-Serif !important;
  font-size: 0.6875rem;
  text-indent: 6px;
  line-height: 1.85;

  &:hover {
    background: #9cbac2;
  }

  ${props => {
    return css`
      background: ${props.isSelected ? 'red' : '#eee'}; // props.isSelected is not defined
    `;
  }}
`;


<Select
  components={{
    Option: ({ children, innerProps, innerRef }) => (
      <Option ref={innerRef} {...innerProps}>
        {children}
      </Option>
    ),
  }}
  styles={reactSelectStyles} // Tried styling Option in the styles object, but that didn't work with a custom component
/>

isSelected prop 暴露给 Option 对象,只需要将它传递给你的 Option 组件。

<Select
  components={{
    Option: ({ children, innerProps, innerRef, ...rest }) => (
      <Option ref={innerRef} {...innerProps} {...rest}> // isSelected passed with `rest`
        {children}
      </Option>
    )
  }}
/>