Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用React和样式化组件传播道具TypeScript_Reactjs_Typescript_Styled Components - Fatal编程技术网

Reactjs 使用React和样式化组件传播道具TypeScript

Reactjs 使用React和样式化组件传播道具TypeScript,reactjs,typescript,styled-components,Reactjs,Typescript,Styled Components,我似乎很难在一个使用StyledComponents的组件中传播道具。每当我试图传递接口中未定义的道具(例如,样式标记)时,我都会得到一个错误。 以下是我当前的实现: interface IParagraphProps { text: string; } const StyledParagraph = styled.p` max-width: 90%; text-overflow: ellipsis; white-space: nowrap; overflow: hidde

我似乎很难在一个使用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;

})

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

const Card = () => {
  return (
        <Paragraph
          text="whatever"
        />)
};
如果你想匹配所有可能的道具,你可以这样做:

type IParagraphProps =  {
  text: string;
} & React.ComponentProps<typeof StyledParagraph>
类型iParGraphProps={
文本:字符串;
}&React.ComponentProps

这与第一个答案类似,但使用的是界面而不是类型:

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

type IParagraphProps =  {
  text: string;
} & React.ComponentProps<typeof StyledParagraph>
类型iParGraphProps={ 文本:字符串; }&React.ComponentProps

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

interface IParagraphProps extends React.ComponentPropsWithoutRef<typeof StyledParagraph> {
  text: string
}
接口iParGraphProps扩展了React.ComponentPropsWithoutRef{
文本:字符串
}
^^^现在,这个组件的道具被指定为StyledParagraph接受的每个道具。如果您还想允许引用,可以将ComponentPropsWithoutRef更改为ComponentPropsWithRef并使用


来源:

您的错误发生在哪里?在这个组件内部还是在另一个调用这个组件的组件中?仅此组件没有错误。另一个组件使用此组件。示例:您能提供调用代码吗?使用调用代码编辑答案。这是因为段落函数将道具接受为iParGraphProps类型,并且没有任何
样式的定义。在您的卡片组件中,您将样式设置为段落的一个道具,而段落的定义中不存在这种道具,即iParagraphPropsys,但我希望传播这些道具。例如,如果我想向它传递一个tabIndex,那么在接口中声明它是没有意义的。或者,如果我有一个按钮,声明禁用和onClick道具…已编辑。我不知道是否有办法让它与界面一起工作,谢谢你的编辑!如果我可以问的话,没有接口它怎么工作?我不明白你的意思,这里我使用了一个类型,所以我没有使用接口
interface IParagraphProps extends React.ComponentPropsWithoutRef<typeof StyledParagraph> {
  text: string
}