【发布时间】:2020-01-25 08:48:40
【问题描述】:
我对 Typescript 还很陌生,并使用 Typescript 创建了一个 React 应用程序。我在将道具从一个组件传递到另一个组件时遇到了一些麻烦。我在下面提供了一个示例,我的问题是关于组件的默认道具。
当我在父组件中调用子组件时,出现错误:
Type '{}' is missing the following properties from type 'IProps': className, disabled ts(2739)
我认为因为我的子组件上有默认的 props,所以当从其他组件调用该组件时,它们会填补任何缺失的 props。
我知道我可以使用className?: string 在我的子组件中的接口IProps 中将单个道具设为可选,但这不是我正在寻找的解决方案,因为它带来的问题多于解决的问题。
当我从另一个组件(如下所示)调用子组件时,我宁愿不必注意每个默认道具,因为对于某些组件,我有很多道具:
<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
【问题讨论】:
标签: reactjs typescript