【问题标题】:Spreading Props TypeScript with React and Styled Components使用 React 和样式化组件传播道具 TypeScript
【发布时间】:2021-01-13 12:00:08
【问题描述】:

我似乎在使用 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 &amp; IParagraphProps'. 以及我使用这个组件的地方:

const Card = () => {
  return (
        <Paragraph
            style={{ marginTop: "1rem" }}
          text="whatever"
        />)

};

【问题讨论】:

  • 您的错误发生在哪里?在这个组件内部还是在另一个调用这个组件的组件中?我没有这个组件的错误
  • 另一个组件使用这个。示例:
  • 能否提供调用代码?
  • 用调用代码编辑了答案。
  • 这是因为 Paragraph 函数接受 props 作为 IParagraphProps 类型并且没有任何style 的定义。在您的 Card 组件中,您将 style 设置为 Paragraph 的属性之一,该属性在其定义中不存在,即 IParagraphProps

标签: reactjs typescript styled-components


【解决方案1】:

这类似于第一个答案,但使用接口而不是类型:

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

类型 IParagraphProps = { 文本:字符串; } & React.ComponentProps

如果您希望能够将文本以外的任何道具传播到 StyledParagraph,您需要在 IParagraphProps 接口中指定它可以接受 StyledParagraph 的任何道具。

interface IParagraphProps extends React.ComponentPropsWithoutRef<typeof StyledParagraph> {
  text: string
}

^^^ 现在该组件的道具被指定为text: string + StyledParagraph 接受的每个道具。如果您也想允许引用,您可以将 ComponentPropsWithoutRef 更改为 ComponentPropsWithRef 并使用React.forwardRef

来源:https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/basic_type_example/#useful-react-prop-type-examples

【讨论】:

    【解决方案2】:

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

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

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

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

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

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

    【讨论】:

    • 是的,但我正在寻找传播道具。例如,如果我想将 tabIndex 传递给它,那么在接口中声明它是没有意义的。或者,如果我有一个 Button,则声明一个 disabled 和 onClick 属性......
    • 已编辑。我不知道是否有办法让它与界面一起工作
    • 感谢编辑!如果我可以问的话,如果没有界面,它会如何工作?
    • 我不明白你的意思,这里我使用了一个类型所以我没有使用接口
    猜你喜欢
    • 2019-04-13
    • 2021-12-13
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 2019-11-11
    • 2020-06-03
    • 2020-05-26
    • 2021-09-11
    相关资源
    最近更新 更多