【问题标题】:ReactTS extend type by dynamic Component Props?ReactTS 通过动态组件道具扩展类型?
【发布时间】:2019-10-07 18:49:49
【问题描述】:

是否有可能有一个 React 组件,它可以动态地找出它得到了什么道具?

例子:

type BaseType = {
   baseProp?: ...
   as?: ...
}

type Extended = {
   extendedProp?: ...
}

<Base /> // expected props => { baseProp }
<Base as={ExtendedComponent} extendedProp={...} /> // expected props => { baseProp, extendedProp } 

【问题讨论】:

    标签: reactjs typescript typescript-typings


    【解决方案1】:

    我们可以从this 的答案中得到提示,使用交叉点首先从as 推断道具的类型,然后使用这些道具来验证任何额外的属性:

    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" /> 
    

    【讨论】:

    • 哇...已经尝试了好几个小时... :D。认为有一个解决方案,因为这可以在编译时处理。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2019-06-26
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    相关资源
    最近更新 更多