【问题标题】:How to evaluate the passed prop to the styled component using react and typescript?如何使用 react 和 typescript 评估传递给样式化组件的 prop?
【发布时间】:2020-06-03 16:23:17
【问题描述】:

如果 state active 为 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}};

`;

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

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

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

    所以你的代码应该是这样的:

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

    【讨论】:

    • 嗯,在批准后意识到背景颜色没有使用道具应用。
    • 啊,是的,对不起,没有注意到你已经用({ active }) 解构了道具,而不是仅仅通过(props)。您可以通过将参数设置为({ active, ...props }) 来纠正此问题,这将确保您的其余道具(active 除外)在props 对象中可用。我更新了我的答案以反映这一点。此外,请确保您的主题可用且设置正确。
    猜你喜欢
    • 2019-07-25
    • 2019-06-26
    • 2019-11-12
    • 2021-01-13
    • 2020-05-22
    • 1970-01-01
    • 2021-09-11
    • 2020-06-06
    • 2020-06-03
    相关资源
    最近更新 更多