【问题标题】:How to write an interface that is automatically extended based on a component prop如何编写一个基于组件prop自动扩展的接口
【发布时间】:2020-01-16 17:20:57
【问题描述】:

假设我有一个Button 组件。它有一个对应的ButtonProps接口。

interface ButtonProps {
  component?: ComponentType;
  label: ReactNode;
  onClick?: (evt: React.MouseEvent<HTMLButtonElement>) => void;
}

如何编写ButtonProps,使其自动构建以接受所有作为component 属性传递的道具?例如,

import { Link } from 'react-router-dom';

<Button
  component={Link}
  label="Home"
  to="/home"
/>

在上面的 sn-p 中,我希望 Button 的输入方式能够理解并接受 to 属性,因为它是在 Link 上定义的属性,它作为component道具。

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    这是我解决您问题的第一种方法如下,但是您必须修改继承按钮道具的道具...也许我可以帮助您提出解决方案:

    Link.js

    interface LinkProps {
      label: React.ReactNode;
      to: string;
    }
    
    const Link: React.FC<LinkProps> = ({label, to}) => 
      <React.Fragment>
        <a href={to}>{label}</a>
      </React.Fragment>;
    

    Button.js

    type ButtonProps<T extends {}> = T & {
      Component?: React.ComponentType<T>;
      onClick?: (evt: React.MouseEvent<HTMLButtonElement>) => void;
    };
    
    const Button: React.FC<ButtonProps<LinkProps>> = ({Component , ...rest}) => 
      <button>
        <Component {...rest} />
      </button>
    

    我附上the link where I was doing the tests

    【讨论】:

      【解决方案2】:

      试试下面的代码:

      <Button
          component={Link}
          {...{
              label: "Home"
              to: "/home"
          }}
      />
      

      您在 {...{ }} 中传递的任何内容都将作为道具传递给链接。如果您有自定义组件,请确保将它们传入。

      【讨论】:

      • 这并不能真正回答问题。例如,ButtonProps 仍然无法理解并正确键入 to 属性。
      猜你喜欢
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 2010-10-26
      相关资源
      最近更新 更多