【问题标题】:Change style of styled component for selected Item更改选定项目的样式组件的样式
【发布时间】:2020-10-11 17:24:35
【问题描述】:

我想更改所选组件的背景和文本颜色。

我使用了样式组件并创建了 isSelected,但是不知道如何使用 isSelected 更改背景和文本颜色。

如何切换它的值?

我有这样的组件:

const Container = styled.div`
  width: auto;
  cursor: pointer;
  :hover {
    background-color: #ccc;
    border-radius: 5px;
  }

  ${({ isSelected }) =>
    isSelected &&
    `
    background-color: #b4b4b4`}

`;

const SomeText = styled.span`
  color: #000000

    ${({ isSelected }) =>
        isSelected &&
        `
        color: #ffffff`}
`;

const MessageRoom = ({ item, onClick }) => {
 return (
  <Container onClick={onClick}>
   <SomeText>{item.text}</SomeText>
  </Container>
 )
};

上面的组件是列表项,下面是父组件,如:

return (
    <div>
        {list.map(item => {
          return <MessageRoom item={item} key={item.id} onClick={onItemClick}/>;
        })}
    </div>
  );

任何帮助将不胜感激。

编辑:

const MessageRoom = ({ item, onClick }) => {
 const [isSelected, setIsSelected] = useState(false);

 return (
  <Container isSelected={isSelected} onClick={onClick}>
   <SomeText isSelected={isSelected}>{item.text}</SomeText>
  </Container>
 )
};

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    样式化的组件在其他方面都很好,但 SomeText 只是缺少一个分号:

    const SomeText = styled.span`
      color: #000000;
      /*            ^^ */
      ${({ isSelected }) => isSelected && `color: #ffffff`}
    `;
    

    由于isSelected 为真时应用的样式不使用任何变量,因此您也可以将反引号更改为普通引号:

    const SomeText = styled.span`
      color: #000000;
      /*            ^^ */
      ${({ isSelected }) => isSelected && "color: #ffffff"}
    `;
    

    同样适用于Container

    要切换样式,您只需将isSelected 作为道具传递给SomeTextContainer,例如

    const MessageRoom = ({ item, onClick }) => {
      return (
        <Container isSelected={true} onClick={onClick}>
          <SomeText isSelected={true}>{item.text}</SomeText>
        </Container>
      );
    };
    

    如何计算isSelected 的值由您自己决定。

    【讨论】:

    • 这就是问题,如何计算 isSelected 值。不知道如何切换?
    • 我会把你推荐给Intro to React
    猜你喜欢
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    相关资源
    最近更新 更多