首页 > 解决方案 > 如何创建动态样式的组件?

问题描述

我想要实现的是这样的:

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

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

标签: reactjsstyled-componentsemotion

解决方案


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

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

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


推荐阅读