【发布时间】:2021-11-10 09:27:12
【问题描述】:
我想要实现的是创建通用类型的组件,它可以接受不同的道具(基于它在项目中的使用),然后最终输出它的子道具和所有给定的道具(流通)+可能是一些新的常量(将根据道具计算),如下所示:
const bonus1 = { offerId: 1, offerDate: 1911 }
const bonus2 = { offerId: 2, timeLeft: 100 }
const bonus3 = { offerId: 3, offerDate: 1991, isActive: true }
<Bonus {...bonus1}>
{({ offerId, offerDate, onClick }) => {})
</Bonus>
<Bonus {...bonus2}>
{({ offerId, timeLeft, onClick }) => {})
</Bonus>
<Bonus {...bonus3}>
{({ offerId, offerDate, isActive, onClick }) => {})
</Bonus>
我已经准备了一些常见的类型,其中包含我知道每个 bonus 都会有的字段,例如:offerId:
type BonusCommon = { offerId: number }
现在组件类型:
type BonusProps<T> = {
children: (renderProps: RenderProps<T>) => ReactNode
} & T
type RenderProps<T> = {
onClick: () => void
} & T // here is what I thought would work, ie. pass to `children` all the input props
还有组件本身:
const Bonus = <T extends BonusCommon>({
children,
offerId,
...rest, // the rest of the input props
}: BonusProps<T>) => {
const onClick = () => {} // do something with available props
return (
<>
children({ // TS ERROR!
onClick,
offerId,
...rest
})
</>
)
}
我没有真正使它起作用的想法,因为目前有一个错误说:'T' could be instantiated with a different subtype of constraint 'BonusCommon'
【问题讨论】:
标签: reactjs typescript typescript-generics