我对 Typescript 和使用 Typescript 创建 React 应用程序相当陌生。我在将道具从一个组件传递到另一个组件时遇到了一些麻烦。我在下面提供了一个示例,我的问题是围绕组件的默认道具。
当我在父组件中调用子组件时,出现错误:
Type '{}' is missing the following properties from type 'IProps': className, disabled ts(2739)
我认为因为我的子组件有默认的 props,所以当从其他组件调用该组件时,它们会填充任何缺失的 props。
我知道我可以在界面中将单个道具设置为可选IProps
在我的子组件中使用className?: string
但这不是我正在寻找的解决方案,因为它带来的问题多于它解决的问题。
当我从另一个组件调用子组件时,我不想必须注意每个默认道具,如下所示,对于某些组件,我有很多道具:<Child class={''} disabled={false} />
我确信有一个相当简单的解决方案,但到目前为止我找不到任何方向。欢迎任何建议或指导。
// Parent component:
import React, { FC } from 'react'
import Child from './child'
const Parent: FC = () => {
return (
<Child />
)
}
export default Parent
// Child component:
import React, { FC } from 'react'
interface IProps {
className: string
disabled: boolean
}
const Child: FC<IProps> = ({ className, disabled }: IProps) => {
return (
<button className={className} disabled={disabled}>
Click here
</button>
)
}
Child.defaultProps = {
className: '',
disabled: false,
}
export default Child