如何实现标签不可知的样式化组件?

cl0*_*k3r 9 javascript css reactjs styled-components

如果我想要一个按钮,但仅是它的演示部分,那么如果我这样做:

import styled from 'styled-components'

const Button = styled.button`
  color: red;
  text-align: center;
`
Run Code Online (Sandbox Code Playgroud)

我被迫渲染button标签,但是如果在语义上我需要锚点呢?

typ*_*ror 11

styled-components提供的withComponent功能对于您想要在组件中使用不同标签的情况非常有用。这与 @siddharthkp 在功能上的回答类似,但使用了 API。

文档中的示例:

const Button = styled.button`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

// We're replacing the <button> tag with an <a> tag, but reuse all the same styles
const Link = Button.withComponent('a')

// Use .withComponent together with .extend to both change the tag and use additional styles
const TomatoLink = Link.extend`
  color: tomato;
  border-color: tomato;
`;

render(
  <div>
    <Button>Normal Button</Button>
    <Link>Normal Link</Link>
    <TomatoLink>Tomato Link</TomatoLink>
  </div>
);
Run Code Online (Sandbox Code Playgroud)


Bea*_*ith 9

使用“为”多态的道具在v4

从文档中的示例复制/粘贴:

const Component = styled.div`
  color: red;
`;

render(
  <Component
    as="button"
    onClick={() => alert('It works!')}
  >
    Hello World!
  </Component>
)
Run Code Online (Sandbox Code Playgroud)


小智 5

您也可以将其与锚标记一起使用,没有什么能阻止您。

import styled from 'styled-components'

const Button = styled.a`
  color: red;
  text-align: center;
`
Run Code Online (Sandbox Code Playgroud)

如果您想同时保留两种样式,可以通过拉出样式来重用它们:

import styled from 'styled-components'

const styles = `
  color: red;
  text-align: center;
`

const Button = styled.button`
  ${styles}
`

const LinkButton = styled.a`
  ${styles}
`
Run Code Online (Sandbox Code Playgroud)


cl0*_*k3r 5

我在样式组件问题跟踪器上问了同样的问题:https : //github.com/styled-components/styled-components/issues/494

我发现的当前“解决方案”是:

// agnosticStyled.js
import React from 'react'
import styled from 'styled-components'

export default styled(
  ({tag = 'div', children, ...props}) =>
    React.createElement(tag, props, children)
)
Run Code Online (Sandbox Code Playgroud)

然后在需要时:

import React from 'react'
import styled from './agnosticStyled'

 const Button = styled`
   color: palevioletred;
   text-transform: uppercase;
 `

 export default Button
Run Code Online (Sandbox Code Playgroud)

最后:

import React from 'react'
import Button from './Button'

const Component = () => 
  <div>
    <Button>button</Button>
    <Button tag="button">button</Button>
    <Button tag="a" href="https://google.com">button</Button>
   </div>

export default Component 
Run Code Online (Sandbox Code Playgroud)

这是一个功能完整的示例:https : //codesandbox.io/s/6881pjMLQ