【发布时间】:2021-04-08 14:43:09
【问题描述】:
boxProp 在props 中找不到。
库版本:
├─react@16.13.1
└─ styled-components@5.2.1
【问题讨论】:
标签: javascript reactjs typescript styled-components
boxProp 在props 中找不到。
库版本:
├─react@16.13.1
└─ styled-components@5.2.1
【问题讨论】:
标签: javascript reactjs typescript styled-components
这行不通,因为您实际上并没有将任何道具传递给您的 Box 组件,第一行所做的只是注释您的 Box 组件可以使用哪些道具 - 所以 React 没有关于哪些道具的上下文使用ComponentProps方法时提取。
当您自己注释道具类型时,一个简单的解决方法是执行以下操作:
type BoxProps = { boxProp: boolean }
const Box = styled('div')<BoxProps>
const MyBox: React.FC<BoxProps> = ({ boxProp }) => {
return (
<Box boxProp={boxProp} />
)
}
如果有帮助,请告诉我!
【讨论】:
styled.div 道具,这正是这里想要的
这是我最后一次尝试解决这个问题:
type OwnProps = { boxProps?: boolean };
const Box = styled.div<OwnProps>``;
type CustomBoxProps = StyledComponentProps<'div', DefaultTheme, OwnProps, never>;
export const MyBox: React.FC<CustomBoxProps> = (props) => {
return (<Box {...props} />);
};
很遗憾,必须使用StyledComponentProps。 React.ComponentProps 不适用于 styled-components 界面。他们肯定有问题。
如果这能解决你的问题,请告诉我,它应该
【讨论】:
import styled , { StyledComponentProps, DefaultTheme } from 'styled-components'; 只是为了使其更加不言自明
Box 后面是哪个样式元素,这意味着'div' 的StyledComponentProps<'div' 不应被硬编码。另外,如果我使用OwnProps,我可以写const MyBox: React.FC<OwnProps>。使用React.ComponentProps 的全部意义在于推断所有这些类型。