首页 > 解决方案 > 使用 styled-components 进行条件渲染

问题描述

我在 React 应用程序中使用 styled-components 库,我有这个块,例如:

const Wrapper = styled.div`
  background: red;
`;

如果道具具有设定值,我需要添加一些其他样式,例如:

const Wrapper = styled.div`
  background: red;
  color: white; // color should be added only if this.props.myProps == 'ok'
`;

最好的方法是什么?

标签: reactjsstyled-components

解决方案


对于一种风格:

const Wrapper = styled.div`
    background: red;
    color: ${props => props.myProps === 'ok' && 'white'};
`;

对于多种样式:

const Wrapper = styled.div`
    background: red;
    ${props => {
        if (props.myProps === 'ok') return `
            background-color: black;
            color: white;
        `
    }}
`;

另一种选择是使用styled.css

// Define a pure group of css properties
const okStyle = styled.css`
    background-color: black;
    color: white;
`;

// Reuse okStyle inside a styled component
const Wrapper = styled.div`
    background: red;
    ${props => props.myProps === 'ok' && okStyle}
`;

推荐阅读