【问题标题】:How to apply the same props to multiple styled components?如何将相同的道具应用于多个样式的组件?
【发布时间】:2021-10-30 12:20:05
【问题描述】:

我正在使用styled-components 库来扩展Blueprintjs 库中的标头组件。 H6 组件目前看起来像:

export const DH6 = styled(H6)`
  color: ${(props) => (props.white ? "white" : null)};
  display: ${(props) => (props.flex ? "flex" : null)};
  opacity: ${(props) => (props.opaque ? 0.7 : null)};
  font-weight: ${(props) => (props.heavy ? 500 : 300)};
  text-align: ${(props) => (props.center ? "center" : null)};
  font-style: ${(props) => (props.italics ? "italic" : null)};
  text-decoration: ${(props) => (props.underline ? "underline" : null)};
`;

这很好用。我现在想将相同的道具从D1 应用到D5。有没有办法以 DRY 的方式做到这一点,而不是应付道具?我尝试将道具分配给变量但没有成功:

const generalProps = {
  opacity: ${(props) => (props.opaque ? 0.7 : null)},
  color: ${(props) => (props.white ? "white" : null)},
  display: ${(props) => (props.flex ? "flex" : null)},
  font-weight: ${(props) => (props.heavy ? 500 : 300)},
  text-align: ${(props) => (props.center ? "center" : null)},
  font-style: ${(props) => (props.italics ? "italic" : null)},
  text-decoration: ${(props) => (props.underline ? "underline" : null)}

}

export const DH6 = styled(H6)`
  {...generalProps}
`;

有什么方法可以对styled-components中的变量进行prop赋值吗?

【问题讨论】:

    标签: javascript css reactjs react-native styled-components


    【解决方案1】:

    作为一个简单的例子,你可以使用

    import styled, {css} from 'styled-components'
    
    const GlobalStyles = css`
      color: ${(props) => (props.white ? "white" : null)};
      display: ${(props) => (props.flex ? "flex" : null)};
      opacity: ${(props) => (props.opaque ? 0.7 : null)};
      font-weight: ${(props) => (props.heavy ? 500 : 300)};
      text-align: ${(props) => (props.center ? "center" : null)};
      font-style: ${(props) => (props.italics ? "italic" : null)};
      text-decoration: ${(props) => (props.underline ? "underline" : null)};
    `
    
    const StyledDiv = styled.div`
     ${GlobalStyles}
     // Other Styles
    `
    

    你要做的是从styled-components导入css
    有了它,您可以生成特定的 css 并将其作为模板文字返回 see the document
    并且为了可重用性,您通常可以使用${value},它相当于Spread Operator(或{...value})用于样式组件

    【讨论】:

    • 我很乐意提供帮助。
    猜你喜欢
    • 2019-07-07
    • 2021-11-09
    • 2021-09-11
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 2023-02-04
    • 2021-09-12
    • 1970-01-01
    相关资源
    最近更新 更多