簡體   English   中英

如何使用 react 和 typescript 評估傳遞給樣式化組件的道具?

[英]How to evaluate the passed prop to the styled component using react and typescript?

如果 state active 為真,我想為樣式化的組件 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}};

`;

這不是正確的語法。 有人可以幫我解決這個問題嗎?謝謝。

您可以將模板文字嵌套在模板文字中,只要它們位於插值表達式塊 ( ${...} ) 內。

所以你的代碼應該是這樣的:

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

`;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM