reactjs - 使用 React 和样式化组件传播道具 TypeScript
问题描述
我似乎在使用 StyledComponents 的组件中传播道具时遇到了麻烦。每当我尝试传递未在界面中定义的道具(例如样式标签)时,都会出现错误。这是我当前的实现:
interface IParagraphProps {
text: string;
}
const StyledParagraph = styled.p`
max-width: 90%;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
`;
const Paragraph = (props: IParagraphProps) => {
const { text, ...rest } = props;
return (
<StyledParagraph {...rest}>{text}</StyledParagraph>
)
};
export default Paragraph;
编辑:这是错误: Property 'style' does not exist on type 'IntrinsicAttributes & IParagraphProps'.
以及我使用此组件的地方:
const Card = () => {
return (
<Paragraph
style={{ marginTop: "1rem" }}
text="whatever"
/>)
};
解决方案
您为 Paragraph 组件提供了一个样式属性,但是该组件只需要一个文本属性。您应该删除该属性:
const Card = () => {
return (
<Paragraph
text="whatever"
/>)
};
或者您应该将该属性添加到您的组件中:
interface IParagraphProps {
text: string;
style: React.CSSProperties;
}
如果你想匹配整个可能的道具,你可以这样做:
type IParagraphProps = {
text: string;
} & React.ComponentProps<typeof StyledParagraph>
推荐阅读
- reactjs - 如果google-,maps-react中Polygon中的当前位置如何调用函数?
- python - 请更正以下错误我无法在模型中添加数据
- ubuntu-14.04 - 如何修复 Ubuntu 中的 Postgresql-11 安装失败错误
- sql-server - NCHAR 的 Debezium SQL Server 连接器值
- c# - 如何处理'包还原失败。!错误?
- odoo-14 - 如何计算 One2many 字段中的行数
- javascript - 如何自定义/编辑 shopify 管理模板?
- typescript - 为什么 TypeScript 不能断言一系列可空值同时都是非空的?
- python - 如何添加公会用户 Discord
- javascript - 如何使用 D3JS 使用多个数组创建树?