gpt4 book ai didi

reactjs - typescript 将样式化的组件 Prop 与父级 Prop 合并

转载 作者:行者123 更新时间:2023-12-05 01:33:00 26 4
gpt4 key购买 nike

我有一个看起来像这样的样式组件:

interface BoxProps {
color?: string;
backgroundColor?: string;
borderColor?: string;
}

export const Box = styled.div<BoxProps>`
position: relative;
padding: 0.75rem 1.25rem;
margin-bottom: 1rem;
border: 1px solid transparent;
border-radius: 0.25rem;
text-align: left;
color: ${(props) => props.color};
background-color: ${(props) => props.backgroundColor};
border-color: ${(props) => props.borderColor};
`;

它被包裹在另一个组件中:

export const Container: React.FC<ContainerProps> = ({
variant,
children,
...props
}) => {
const { color, backgroundColor, borderColor } = variantColor(variant);

return (
<div>
<Box
color={color}
backgroundColor={backgroundColor}
borderColor={borderColor}
{...props}
>
{children}
</Box>
<p></p>
// ...
</div>
);
};

如果我添加 StyledComponent<"div", any, BoxProps, never>React.FC<ContainerProps> :

React.FC<ContainerProps & StyledComponent<"div", any, BoxProps, never>>

传播 Prop 会给我以下错误: Rest types may only be created from object types我试过 React.HTMLAttributes<{}> & typeof Box.propTypesReact.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>没有运气......

有没有办法将样式组件 Prop 与父 Prop 合并?

谢谢!

最佳答案

styled.div只呈现 div它接受任何属性 div会接受来自 BoxProps 的 + 您的属性.您可以使用 React.HTMLAttributes<HTMLElementYouNeed> 获取描述 JSX 元素属性的类型在这种情况下 React.HTMLAttributes<HTMLDivElement> , 所以 Box 的 Prop 现在是这个加上 BoxProps :

React.FC<ContainerProps & React.HTMLAttributes<HTMLDivElement> & BoxProps>

如果你懒得写这个,你可以在项目的某个文件中创建一个实用程序命名空间:

declare namespace HTMLProps {
type div = React.HTMLAttributes<HTMLDivProps>
// Maybe define props for other html elements if you need
}
export default HTMLProps

然后导入并使用

React.FC<ContainerProps & HTMLProps.div & BoxProps>

关于reactjs - typescript 将样式化的组件 Prop 与父级 Prop 合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64943557/

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