首页 > 解决方案 > 使用 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"
        />)

};

标签: reactjstypescriptstyled-components

解决方案


您为 Paragraph 组件提供了一个样式属性,但是该组件只需要一个文本属性。您应该删除该属性:

const Card = () => {
  return (
        <Paragraph
          text="whatever"
        />)
};

或者您应该将该属性添加到您的组件中:

interface IParagraphProps {
  text: string;
  style: React.CSSProperties;
}

如果你想匹配整个可能的道具,你可以这样做:

type IParagraphProps =  {
  text: string;
} & React.ComponentProps<typeof StyledParagraph>

推荐阅读