动态样式组件作为道具传递

时间:2021-06-05 22:07:31

标签: reactjs styled-components

目标是在函数内设置 prop 的样式(如果 prop 存在)。

更具体地说,我基本上将一个图标(来自 $ docker start -ai $(docker ps -q -l) )作为道具传递给它,它应该为该图标添加样式。

这适用于警告:

styled-icons

我是这样称呼它的:

const InputRounded = ({ type, placeholder, icon }) => {
  const Icon = styled(icon)`
    color: #807da0;
    width: 1.75rem;
    margin: 0 1.25rem 0 0.75rem;
  `

  return (
    <Container>
      <Input type={type} placeholder={placeholder} />
      <Icon />
    </Container>
  )
}

我知道不应该在函数内创建组件,但我已经尝试了很多方法,但还没有达到任何目的。任何对更好方法的帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以非常简单地将 style 属性传递给 icon

const InputRounded = ({ type, placeholder, icon: Icon }) => {
  return (
    <Container>
      <Input type={type} placeholder={placeholder} />
      <Icon style={{ color: '#807da0', ... }} />
    </Container>
  )
}

答案 1 :(得分:0)

你可能可以在 React 中使用 cloneElement 方法


return (
  <> 
    { React.cloneElement( icon, [props] }
  </>
)

类似于

<element.type {...element.props} {...props}>{children}</element.type>

要覆盖某些值,您可以执行内联样式。

或者你也可以使用一些 css 类来覆盖选择器。

  • 如果您打算使用 styled-icons
  • 你可以直接向它提供道具。
  • 样式图标接受 <svg /> 元素的所有有效道具

https://github.com/styled-icons/styled-icons#props

相关问题