如何使用react和Typescript评估传递给样式组件的prop?

时间:2020-06-02 09:27:37

标签: reactjs typescript

如果状态为true,我想为样式化的div组件添加背景色。

我正在这样做

function Main() {
    const [active, setActive] = useState(false);
    return (
        <ChildComponent 
            active={active}/>
    );
}


const ChildComponent = styled.div<{ active?: boolean }>`
    height: 100%;
    ${({ active }) => active && 'background-color: grey';}
`;

这很好。但是我不仅希望将字符串灰色传递给背景颜色,还希望传递如下所示的道具。

const ChildComponent = styled.div<{ active?: boolean }>`
    height: 100%;
    ${({ active }) => active && 'background-color:'${(props: any) => 
    props.theme.colors.grey.light3}};

`;

这不是正确的语法。有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

您可以将模板文字嵌套在模板文字中,只要它们位于插值表达式块(${...})内即可。

所以您的代码应如下所示:

const ChildComponent = styled.div<{ active?: boolean }>`
    height: 100%;
    ${({ active, ...props }) => active && `background-color: ${(props: any) => 
    props.theme.colors.grey.light3}`};

`;
相关问题