【问题标题】:styled-component - passing props best practices [closed]styled-component - 传递道具最佳实践
【发布时间】: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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-11-20
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多