reactjs - 基于属性的动态样式组件标签
我正在尝试使用 styled components 创建一个动态标签。该标签是通过 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 成为一个动态属性。
答案#1
你可以像这样使用“as”多态属性:
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;
看看我根据你的代码整理的这个简单的 CodeSandbox
