本文介绍了ReactTS 通过动态组件道具扩展类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能有一个 React 组件可以动态地找出它有什么道具?
Is it possible to have a React component what can find out dynamically what props its got?
示例:
type BaseType = {
baseProp?: ...
as?: ...
}
type Extended = {
extendedProp?: ...
}
<Base /> // expected props => { baseProp }
<Base as={ExtendedComponent} extendedProp={...} /> // expected props => { baseProp, extendedProp }
推荐答案
从 this 答案我们可以,使用交集首先从 as
推断道具的类型,然后使用这些道具来验证任何额外的属性:
Taking a cue from this answer we can, using intersections first infer the type of the props from as
and then use those props to validate any extra properties:
type BaseType = {
baseProp?: number
}
type Extended = {
extendedProp?: string
}
declare const ExtendedComponent: React.FC<Extended>
function Base<T = {}>(p: BaseType & { as? : React.ComponentType<T>} & T): React.ReactElement{
if(p.as) {
const Child = p.as;
return <div>{p.baseProp}<Child {...p as T}></Child></div>
}else {
return <div>{p.baseProp}</div>
}
}
let s = <Base /> // expected props => { baseProp }
let a = <Base as={ExtendedComponent} extendedProp="a" />
这篇关于ReactTS 通过动态组件道具扩展类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!