【发布时间】: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<Link, unknown>
标签: reactjs typescript react-router material-ui react-router-dom