简体   繁体   English

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

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

We're using a custom Emotion component, and the documentation says that the same properties are passed to customer components, but they don't seem to be.我们正在使用自定义的 Emotion 组件,文档说相同的属性被传递给客户组件,但它们似乎没有。 isSelected and other properties don't seem to be there either. 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 is exposed to the Option object, just need to pass it to your Option component. isSelected prop 暴露给Option对象,只需要将它传递给你的Option组件。

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

编辑 react-codesandboxer-example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM