Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.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 将TypeScript React组件嵌套在另一个组件中_Reactjs_Typescript - Fatal编程技术网

Reactjs 将TypeScript React组件嵌套在另一个组件中

Reactjs 将TypeScript React组件嵌套在另一个组件中,reactjs,typescript,Reactjs,Typescript,所以我试图在另一个组件中嵌套一个TypeScript React组件,但它会抱怨类型。它似乎希望我将所有道具添加到父界面中 有没有一种方法可以做到这一点,而不必在子组件接口中列出我的所有类型,然后还要将这些类型添加到父组件接口 注意:我在下面的示例中使用样式化组件 interface IField { children: React.ReactNode } export function Field({ children, htmlFor, label, required, ...prop

所以我试图在另一个组件中嵌套一个TypeScript React组件,但它会抱怨类型。它似乎希望我将所有道具添加到父界面中

有没有一种方法可以做到这一点,而不必在子组件接口中列出我的所有类型,然后还要将这些类型添加到父组件接口

注意:我在下面的示例中使用样式化组件

interface IField {
  children: React.ReactNode
}

export function Field({ children, htmlFor, label, required, ...props }: IField) {
  return (
    <FormField {...props}>
      <Label htmlFor={htmlFor} label={label} required={required}/>
      {children}
    </FormField>
  )
}

interface ILabel {
  htmlFor: string
  label: string
  required?: boolean
}

export function Label({ htmlFor, label, required }: ILabel) {
  return (
    <FormLabel htmlFor={htmlFor}>
      {label}
      {required && (
        <Required />
      )}
    </FormLabel>
  )
}

提前谢谢你的帮助

为了避免将属性从子接口添加回父组件接口,可以使用
扩展
(请参阅文档)

之后,您可以使用子组件上的
{…props}
解构器,将
props
从父组件传递到子组件

最后,如果您使用的是TypeScript,那么最好使用
React.FunctionComponent
键入,以避免手动键入
子项

您可以查看这个简化的工作示例:

我试着改编你下面的片段

从“React”导入React;
接口IField扩展了ILabel{
}
导出常量字段:React.FunctionComponent=(props)=>{
返回(
{props.children}
)
};
接口ILabel{
htmlFor:字符串
标签:字符串
必需?:布尔值
}
导出常量标签:React.FunctionComponent=(props)=>{
返回(
{props.label}
{props.required&()}
)
};

是否在
字段的返回上抱怨?看起来您没有为
传递必需的参数
htmlFor,也没有正确地传递必需的参数:
props.required
vs
required
——因为您没有直接分解该键。哎呀,我刚刚修复了
required
prop。它在
表单字段
中的
标签
组件上抱怨。这让事情变得更清楚了,确实是一个非常简洁的答案!)但是,我确实有一个问题,您使用
props
而不是像我在上面的示例中所做的那样对它们进行分解,有什么特别的原因吗?很高兴它对您有所帮助,别忘了接受答案;)关于
道具的解构
我想这确实是一个偏好的问题,我选择使用
道具.myProperty
,因为我发现它更易于维护,因此如果我添加任何新道具,我不必将其添加到解构的
道具
,但这就是我,最后一个问题是,如果我想扩展多个接口,它是否像用逗号分隔它们那样简单?示例:
接口IField扩展了ILabel,接口{}
是的,你得到了!太棒了!我在这里提出了一个后续问题,如果你想尝试一下,我真的很喜欢你对事情的解释-
Type '{}' is missing the following properties from type 'ILabel': htmlFor, label