【问题标题】:Dynamic styled component tag based on prop基于 prop 的动态样式组件标签
【发布时间】:2019-07-02 17:31:17
【问题描述】:

我正在尝试创建一个带有样式组件的动态标签。标签是通过 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;

我正在努力实现&lt;Container&gt; 标签(现在是div)是基于prop.type 的动态道具。

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:

    你可以使用"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我根据你的代码整理

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 2021-12-18
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      相关资源
      最近更新 更多