首页 > 解决方案 > 如何使用 Material-UI 按钮在 Typescript 函数上实现道具类型?

问题描述

首先,如果我没有正确表达自己,我的借口,我仍然对 Typescript 有点困惑。

我有一个来自 Material-UI 的样式按钮,我不确定如何继续使这个按钮在整个应用程序中可重用。我基本上希望该按钮能够接收诸如此类的道具{buttonText},因此我可以在多个页面中使用它,但具有不同的标签。

import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';

const useStyles = makeStyles({
  backButton: {
    background: 'linear-gradient(45deg, #9AA5B0 30%, #9AA5B0 90%)',
    border: 0,
    borderRadius: 25,
    boxShadow: '0 2px 4px rgba(0, 0, 0, .5)',
    color: 'white',
    fontFamily: 'Poppins, sans-serif',
    fontSize: 15,
    height: 37,
    padding: '0 20px',
    textTransform: 'none',
  },
});

export default function BackButton(): React.ReactElement {
  const classes = useStyles();
  return (
    <Button className={classes.backButton} startIcon={<ChevronLeftIcon />}>
      {buttonText}
    </Button>
  );
}

所以当我在另一个页面中插入按钮组件时,我可以给道具一个值,然后正确的标签会显示在我的按钮上。

<div>
  <PrimaryButton />
  <BackButton label={buttonText}/>
</div>

关于如何使用类型进行这项工作的任何建议?

提前谢谢了!

标签: reactjstypescripttypesmaterial-uireact-props

解决方案


首先,您的组件 BackButton 需要接受道具。

然后你为 props 做一个类型:

export type BackButtonProps = {
  label: string;
};

并添加到您的 BackButton 组件:

export type BackButtonProps = {
  label: string; // or buttonText
  // ...other props
};

export default function BackButton(props: BackButtonProps) {
  const classes = useStyles();
  return (
    <Button className={classes.backButton} startIcon={<ChevronLeftIcon />}>
      {props.label}
    </Button>
  );
}

现在,您的 BackButton 具有具有类型的道具。

使用:

<BackButton label="Custom Label" />

如果库对他的按钮有一个内部类型,你可以扩展这个类型,所以你的类型将通过继承具有所有属性:

import { AnyExistingType } from 'material-ui';

export type BackButtonProps = AnyExistingType & { label: string };


推荐阅读