我对TypeScript和使用TypeScript创建React应用还比较新。我在尝试将属性从一个组件传递到另一个组件时遇到了一些问题。以下是我提供的一个示例,我的问题与组件的默认属性有关。
当我在父组件中调用子组件时,我会收到一个错误:
Type '{}' is missing the following properties from type 'IProps': className, disabled ts(2739)
我以为因为我在子组件中设置了默认属性,所以在从其他组件调用该组件时,缺少的属性会被默认属性填充。
我知道我可以使用className?: string
在child组件中使单个属性变成可选的,但这不是我想要的解决方案,因为它引入了更多的问题。
我不想在调用子组件时注明每个默认属性,像下面这样,因为对于某些组件,我有很多属性:
<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
Child.defaultProps
中进一步下去。 - paulosullivan22