【问题标题】:How to create dynamic styled component?如何创建动态样式的组件?
【发布时间】:2018-11-30 08:43:51
【问题描述】:

我想要实现的是这样的:

import styled from 'react-emotion'

const StyledComponent = styled(({tag}) => tag)`
    // some css styles
`

并像这样使用它:

<StyledComponent tag=div"/>
<StyledComponent tag="p"/>
<StyledComponent tag="ul"/>
// etc

我的期望是它应该生成如下 HTML:

<div class="some-class"></div>
<p class="some-class"></p>
<ul class="some-class"></ul>

实际输出:

div
p
ul

我的问题是,这可以实现还是我错过了什么?

【问题讨论】:

    标签: reactjs styled-components emotion


    【解决方案1】:

    似乎我已经找到了解决问题的方法。为可能遇到相同问题的人分享我的答案。

    我将StyledComponent 声明更改为:

    import styled from 'react-emotion'
    
    const StyledComponent = styled(({tag, children, ...props}) => React.createElement(tag, props, children))`
        // some css styles
    `
    

    这是按预期工作的。

    如果有人有更好的答案,请发帖。谢谢

    【讨论】:

    【解决方案2】:

    你用错了react-emotion,请试试这个。

    const StyledComponent = ({ tag, children, ...props }) => {
      const Container = styled(tag)`
        background-colo: red;
      `;
      return <Container {...props}>{children}</Container>;
    };
    

    演示:https://codesandbox.io/s/lr4xxp3757

    【讨论】:

    • 试过了,但什么也没返回 :(
    • @SanjayJoshi,我已经更新了答案,请检查确认
    猜你喜欢
    • 1970-01-01
    • 2013-12-29
    • 2021-03-26
    • 1970-01-01
    • 2020-12-24
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    相关资源
    最近更新 更多