【问题标题】:Typescript React, How to provide type infomation for a component which recives a custom input component as props?Typescript React,如何为接收自定义输入组件作为道具的组件提供类型信息?
【发布时间】:2020-07-05 18:45:44
【问题描述】:

我如何为CustomComponent 提供组件Foo 作为道具接收的道具类型,CustomComponent 可以是例如CustomInput 组件。我可以使用通用的React.FC<T>,但是如何为 T 设置类型,因为它需要为输入元素的所有属性提供类型(传递 InputProps 不起作用)并且自定义组件也可以是类组件可以接收相同的道具,那么我如何创建接口FooProps,它可以在其中接收自定义组件作为功能或类组件,并且自定义组件获取输入元素的所有属性的道具加上道具@ 987654328@.

interface FooProps {
   customComponent: React.FC<???> // doesn't work
   // other props // works
}

const Foo: React.FC<FooProps> = ({ children, customComponent: CustomComponent }) => {
    
   return (
       <div>
           {children}
           <CustomComponent type="text" styleVariant="primary"/> // compiler complains
       </div>

   )

}


interface InputProps {
  styleVariant: string;
}

const CustomInput: React.FC<InputProps> = ({ styleVariant, ...rest }) => {
   // something to do with styleVariant

   return <input {...rest}/>
}

这是我得到的错误,我希望这个问题可以理解。提前致谢。

Type '{ type: string; styleVariant: string; }' is not assignable to type 'IntrinsicAttributes & { styleVariant: string; } & { children?: ReactNode; }'.
  Property 'type' does not exist on type 'IntrinsicAttributes & { styleVariant: string; } & { children?: ReactNode; }'.ts(2322)

【问题讨论】:

    标签: reactjs typescript typescript-generics


    【解决方案1】:

    看来您需要使用React.HTMLProps

    interface InputProps extends React.HTMLProps<HTMLInputElement> {
       styleVariant: string;
       // type for any other custom props you want to pass
    }
    

    由于自定义组件既可以是函数式组件也可以是类组件,您可以使用React.ComponentType generic,它只是FunctionComponentComponentClass 类型的联合,并且还为props 提供类型参数。

    // you can pass InputProps to the React.ComponentType generic as -
    // type argument for props
    type TCustomComponent = React.ComponentType<InputProps>
    
    interface FooProps {
      customComponent: TCustomComponent
    
     // other props for Foo compoent
    }
    
    
    const Foo: React.FC<FooProps> = ({ children, customComponent: CustomComponent }) => {
        
      return (
        <div>
          {children}
          <CustomComponent type="text" styleVariant="primary"/>
        </div>
     );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多