使用 props 基于其他组件创建样式化组件

Create styled component based on other component with props

P 添加样式效果很好:

const Quotation = styled(P)`
    &::before, &::after {
        content: '"';
    }
`;

但我想做的是使用传递给它的道具 italic=trueP 添加样式。类似于:

const Quotation = styled(P italic=true)`
    &::before, &::after {
        content: '"';
    }
`;

我该怎么做?

你可以像这样做你的组件:

interface Props { children: any , italic ?: boolean }

const P = styled.p<Props>`
    // Style you added.
    font-style: ${({ italic }) => italic ? 'italic' : 'normal'  };
`;

const Quotation = styled(P)`
    &::before, &::after {
        content: '"';
    }
    // Additional style.
`;

用法

render() {
    return (
        <div>
            <Quotation italic={true}> Hello World </Quotation>
        </div>
    )  
}

当您使用 Styled(ComponentA) 扩展组件时,您会继承 props

但是在你的情况下,传递道具可能是不必要的,你可以这样做:

const P = styled.p`
     // style you added.
`;

const Quotation = styled(P)`
    &::before, &::after {
        content: '"';
    }
    font-style: italic; 
    // Additional style.
`;