gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:58:51 24 4
gpt4 key购买 nike

我正在尝试创建一个带有样式组件的动态标签。标签通过 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我根据你的代码放在一起

关于reactjs - 基于 prop 的动态样式组件标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com