【问题标题】:Type of Link component passed as 'component' prop作为“组件”道具传递的链接组件的类型
【发布时间】:2020-06-19 07:38:13
【问题描述】:

我有一个函数组件(带有 TypeScript),假设它被称为 Button。我从 Material-UI 将 Button 作为 BaseButton 导入,对其进行样式设置,添加一些很酷的功能(我在此处删除了不必要的代码)并将其导出为我自己的 Button。后来,当我在代码中的某处使用这个导出的按钮并希望将链接组件(从 react-router-dom 导入)作为“组件”道具传递给这个按钮时。我应该在 ButtonProps 界面中使用什么类型?另外,'to' 属性是否应该指定为字符串?

component/button.tsx

import * as React from 'react';
import { Button as BaseButton } from '@material-ui/core';

interface ButtonProps {
  component: ???;
  to: string;
}

export const Button: React.FC<ButtonProps> = ({ component, to }) => (
  <BaseButton component={component} to={to} />
)

.

some other place

import { Button } from 'components/button';
import { Link } from 'react-router-dom';

(...)
  <Button component={Link} to={'/'} />
(...)

【问题讨论】:

  • component: React.ReactElement 会这样做。但这允许您输入任何反应组件。道具to 我将输入为:H.LocationDescriptor,其中导入为:import * as H from "history"。要进一步限制组件,您可以向其添加以下类型:component: React.Component&lt;Link, unknown&gt;

标签: reactjs typescript react-router material-ui react-router-dom


【解决方案1】:

标签不是可视组件,而是为添加导航功能而制作的包装器, material-ui 是相反的用途 因此像这样的东西应该导航


    export const Button: React.FC<ButtonProps> = ({ to }) => 
      <Link to={to}
        <BaseButton /> // your own styled compnent
      </Link>
     )

【讨论】:

  • 我不太想在我的项目中使用这个解决方案,因为有时按钮会是一个链接,有时是一个常规按钮,有时甚至可能是一个链接。但是聪明的主意:)
猜你喜欢
  • 2020-03-22
  • 1970-01-01
  • 2020-11-09
  • 2021-12-09
  • 2021-09-08
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
相关资源
最近更新 更多