因此,我试图将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>
)
}
错误我得到:
Type '{}' is missing the following properties from type 'ILabel': htmlFor, label
感谢您的任何帮助!
为了避免将属性从子接口添加回父组件接口,可以使用extends
(请参阅TypeScript继承文档)。
之后,您可以通过在props
子组件上使用{...props}
deconstructor将父组件的传递给子组件。
最后,如果您使用的是TypeScript,最好也使用React.FunctionComponent
输入以避免手动输入children
。
您可以查看以下简化的工作示例:https :
//stackblitz.com/edit/react-stackoverflow-60228406
我试图在下面修改您的代码段...
import React from 'react';
interface IField extends ILabel {
}
export const Field: React.FunctionComponent<IField> = (props) => {
return (
<FormField>
<Label {...props} />
{props.children}
</FormField>
)
};
interface ILabel {
htmlFor: string
label: string
required?: boolean
}
export const Label: React.FunctionComponent<ILabel> = (props) => {
return (
<FormLabel htmlFor={props.htmlFor}>
{props.label}
{props.required && (<Required />)}
</FormLabel>
)
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句