【问题标题】:Create new component and inherit styles from styled-component创建新组件并从 styled-component 继承样式
【发布时间】:2019-09-18 20:53:36
【问题描述】:
const Button = styled.button`
  display: inline-block;
  width: 300px;
  background-color: black;
`    

const ButtonHref = styled.a`
  ${Button}
`   

所以我有两个样式组件。我想继承“按钮”样式但创建另一个标签。我使用反应情绪。我该怎么做?

【问题讨论】:

  • 以下是否回答了您的问题?

标签: javascript styled-components emotion


【解决方案1】:

如果您只想要一个与您的Button 具有完全相同样式的a,那么您可以使用<Button as=“a” />

【讨论】:

  • 这是正确答案!你甚至可以做到<Button as={Anchor} /> Anchor 是另一个组件。
【解决方案2】:

这里有几个选项,使用组合、样式化组件或使用道具。第二个选项可能是您想要的,但我也提供了其他两个选项。

1.使用合成

const baseButton = css`
  color: white;
  background-color: black;
`

const fancyButton = css`
  background-color: red;
`

render() {

  return (
    <div>
      <button css={baseButton}></button>
     <button css={[baseButton, fancyButton]}></button>
    </div>
  )
}

第二个按钮将具有baseButtonspecialButton 样式。

或者……

const baseButton = css`
 color: white;
 background-color: black;
`

const fancyButton = css`
 ${baseButton};
 background-color: red;
`

render() {
 return (
   <div>
     <button css={baseButton}></button>
     <button css={fancyButton}></button>
   </div>
 )
}

2。使用样式化组件

const Button = styled.button`
  color: white;
  background-color: black;
`
const Fancy = styled(Button)`
  background-color: red;
`

render() {
  return (
    <div>
      <Button>Button</Button>
      <Fancy>Fancy</Fancy>
    </div>
  )
}

这适用于任何接受 className 属性的组件,button 就是这样做的。

3.使用props

  const Button = styled.button`
    color: white;
    background-color: ${props => props.fancy ? 'red' : 'black'};
  `

  render() {
    return (
      <div>
        <Button>Button</Button>
        <Button fancy>Fancy</Button>
      </div>
    )
  )

【讨论】:

猜你喜欢
  • 2020-06-09
  • 2021-10-31
  • 2021-03-07
  • 2021-09-02
  • 2021-12-19
  • 2019-07-06
  • 2018-12-14
  • 1970-01-01
  • 2021-12-30
相关资源
最近更新 更多