首页 > 解决方案 > styled-component - 传递 props 最佳实践

问题描述

想象这样一个场景:您创建一个主题并将其传递给 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') };
`;

嗯......它看起来很乱。您可以使用对象销毁、伪造的 mixin 或其他任何东西,但是当您在每一行中不断传递函数时,很难保持干净。我想过做这样的事情:

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') };
    `;
  }}
`;

但它也不完美。

有没有更好的方法来解决这个问题?

标签: javascriptcssreactjsstyled-componentscss-in-js

解决方案


好的,我认为文档没有提到它,但显然这样的语法也适用:

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') };
    `
);

它看起来好多了,我认为没有比这更好的了。但是,如果您有一些想法,请随时分享。


推荐阅读