【问题标题】:Create type for component based on props passed [duplicate]根据传递的道具为组件创建类型[重复]
【发布时间】:2019-07-29 18:13:23
【问题描述】:

我正在创建一个如下所示的组件:

<Button component='a' href='/'>
  Link
</Button>

我想获取component 属性的类型定义,所以我可以自动将它包含在Button 组件的属性中。关于Button 组件的接口/类型应该是什么样子的任何想法

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    我以前使用过这种模式。声明 React.ComponentType&lt;T&gt; | string 类型的 component 属性。你的Button 组件应该看起来像这样:

    export interface ButtonProps {
      component?: React.ComponentType<any>; // or React.ReactElement<any>["type"]
      href?: string;
      children?: React.ReactNode;
    }
    
    export function Button(props: ButtonProps) {
      const {
        component: Component = "button", // note: uppercase
        children,
        ...other
      } = props;
    
      return (
        <Component {...other}>
          {children}
        </Component>
      );
    }
    

    【讨论】:

    • 很好,谢谢。但是如何检查按钮组件的类型上是否存在 ...other 道具?
    • @OluwakoredeFashokun any 会覆盖它,但这有点小技巧。也许使用React.ComponentType&lt;React.AnchorHTMLAttributes&lt;HTMLAnchorElement&gt; | React.ButtonHTMLAttributes&lt;HTMLButtonElement&gt;&gt;,或者声明你想要支持的组件上的哪些道具。
    【解决方案2】:

    您的Button 组件可以这样输入:

    import * as React from 'react';
    
    type ButtonProps = {
        component: string,
        href: string,
    }
    type ButtonState = {}
    export default class Button extends React.Component<ButtonProps , ButtonState > {
        constructor(props) {
            super(props);
            this.state = {}
        }
        render() { return <div/> }
    }
    

    我写了一篇关于从头到尾构建TypeScript + React 应用程序的整篇文章,请查看完整的详细信息和解释!

    【讨论】:

      猜你喜欢
      • 2020-03-22
      • 2017-05-26
      • 1970-01-01
      • 2020-06-19
      • 2020-11-04
      • 2019-12-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      相关资源
      最近更新 更多