基于 prop 的动态样式组件标签

Dynamic styled component tag based on prop

我正在尝试创建带有样式组件的动态标签。通过 props 接收标签。

这是代码示例:

import * as React from 'react';
import styled from 'styled-components';

type ContainerProps = {
    children: React.ReactNode,
    type?: 'section' | 'div' | 'article',
}

const Container = styled.div`
  color: ${props => props.theme.primaryColor};
`;

const Icon = styled.div<ContainerProps>`
    background-color: red;
`;

const container: React.FunctionComponent<ContainerProps['children']> = ({ children, type = 'section' }: ContainerProps) => {
    return (
        <Container>
            <{ children }
        </Container>
    );
};

export default container;

我正在努力实现 <Container> 标签(现在是 div)是一个基于 prop.type.

的动态属性

您可以像这样使用 "as" polymorphic prop

import * as React from 'react';
import styled from 'styled-components';

type ContainerProps = {
    children: React.ReactNode,
    type?: 'section' | 'div' | 'article',
}

const Container = styled.div`
  color: ${props => props.theme.primaryColor};
`;

const Icon = styled.div<ContainerProps>`
    background-color: red;
`;

const container: React.FunctionComponent<ContainerProps['children']> = ({ children, type = 'section' }: ContainerProps) => {
    return (
        <Container as={type}>
            { children }
        </Container>
    );
};

export default container;

看到这个simple codesandbox我根据你的代码整理的