我正在尝试创建带有样式化组件的动态标签。标签是通过道具接收的。
这是代码示例:
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
的动态道具。
答案 0 :(得分:0)
您可以使用"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