具有逻辑的可重用样式组件(伪元素)

Reusable styled components (pseudo element) with logic

我已经编写了一些共享样式以跨不同的组件使用,如何根据传递的值或布尔逻辑更改 leftwidth 的值,以便值可以更多动态?

如果可能的话,我不希望它在实际组件中作为 prop 传递 <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}
  }
`

您可以改用函数:

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}
`

这是结果: