【发布时间】:2021-03-31 04:37:34
【问题描述】:
想象一下这样的场景:您创建一个主题并将其传递给 ThemeProvider。 它可能看起来像这样:
const theme = {
palette: {primary: {main: 'blue', contrastText: 'white'}, surface: 'gray'},
borderWidth: '1px',
shadowMixin: size => `0px 0px ${size} black`
}
然后你创建一个组件:
const Something = styled.div`
color: ${props => props.theme.palette.primary.contrastText};
background: ${({theme}) => theme.palette.surface};
border: ${props => props.theme.borderWidth} solid ${({theme}) => theme.palette.primary.main};
box-shadow: ${props => props.theme.shadowMixin('10px') };
`;
嗯……它看起来很乱。您可以使用对象破坏、假混入或其他任何方法,但是当您在每一行中不断传递函数时,很难保持干净。我想过做这样的事情:
const Something = styled.div`
${({ theme: { palette, borderWidth, shadowMixin } }) => {
css`
color: ${palette.primary.contrastText};
background: ${palette.surface};
border: ${borderWidth} solid ${palette.primary.main};
box-shadow: ${ shadowMixin('10px') };
`;
}}
`;
但它也不完美。
有没有更好的方法来解决这个问题?
【问题讨论】:
标签: javascript css reactjs styled-components css-in-js