我已經撰寫了一些共享樣式以在不同組件中使用,我如何更改left或width基于傳遞的值或布爾邏輯的值,以便這些值更具動態性?
如果可能的話,我不希望它作為實際組件中的道具傳遞<bar left="20" />,而只是在宣告的樣式中傳遞。
const shared = css`
::after {
content: '';
left: 0;
width: 100%;
${(props) => props.beta &&
`
top: 0;
`
}
`
const foo = styled.div`
${shared}
`
const bar = styled.div`
${shared}
${child} {
${shared}
}
`
uj5u.com熱心網友回復:
您可以改用函式:
const getShared = (props) => css`
::after {
content: '';
left: ${props.left || '0'};
width: ${props.width || '100%'};
${(otherProps) => otherProps.beta &&
`
top: 0;
`
}
`
const foo = styled.div`
${(props) => getShared(props)}
`
const bar = styled.div`
${(props) => getShared(props)}
${child} {
${(props) => getShared(props)}
}
`
如果你想簡單地覆寫共享 css,這里是一個簡單的例子:
<div>
{/* this is a div that uses shared css */}
<div css={shared}>this is shared css</div>
{/* this is a div that uses shared css in his styling*/}
<FirstContainer>container extends shared css</FirstContainer>
{/* this is a div that uses shared css in his styling but overrides border color using a prop*/}
<SecondContainer borderColor="red">container overrriding the shared css</SecondContainer>
</div>
這是樣式:
// this is the shared css
export const shared = css`
width: 100px;
height: 100px;
border: solid 1px green;
margin: 40px;
`
// div using the shared css
export const FirstContainer = styled.div`
${shared}
`
// div using the shared css but overriding border color
// props contains all the properties passed to the SecondContainer component (like left in bar component)
export const SecondContainer = styled.div`
${shared}
border-color: ${(props) => props.borderColor}
`
這是結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/449287.html
下一篇:如何設定段落的字數限制?
