创建新组件并从 styled-component 继承样式

新手上路,请多包涵
const Button = styled.button`
  display: inline-block;
  width: 300px;
  background-color: black;
`

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

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

原文由 Lamer_2005 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 841
1 个回答

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

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>
    )
  )

原文由 Brett DeWoody 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏