【问题标题】:How to style the selected item in React-Select when using a custom component?使用自定义组件时如何在 React-Select 中设置所选项目的样式?
【发布时间】:2020-07-01 03:48:12
【问题描述】:

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

【问题讨论】:

  • 你能做一个在线演示吗?如果我们能够重现整个环境,我相信它会很快解决
  • 相关样式组件文档:referring-to-other-components

标签: javascript reactjs react-select emotion


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-07-21
    • 1970-01-01
    • 2018-07-30
    • 2018-08-26
    • 2021-02-23
    • 1970-01-01
    • 2021-03-02
    • 2019-03-01
    • 2020-02-17
    相关资源
    最近更新 更多