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

时间:2020-03-20 00:11:43

标签: javascript reactjs react-select emotion

我们使用的是自定义的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
/>

1 个答案:

答案 0 :(得分:1)

isSelected属性暴露于Option对象,只需将其传递给您的Option组件。

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

Edit react-codesandboxer-example