【问题标题】:How to implement prop types on a Typescript function with a Material-UI button?如何使用 Material-UI 按钮在 Typescript 函数上实现道具类型?
【发布时间】:2021-05-13 09:36:18
【问题描述】:

首先,如果我没有正确表达自己,我的借口,我仍然对 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>

关于如何使用类型来完成这项工作的任何建议?

非常感谢!

【问题讨论】:

    标签: reactjs typescript types material-ui react-props


    【解决方案1】:

    首先,你的组件 BackButton 需要接受 props。

    然后你为 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 &amp; { label: string };

    【讨论】:

    • 并非所有英雄都穿着斗篷。谢谢!我终于明白类型是如何工作的了!
    猜你喜欢
    • 2020-06-24
    • 2018-02-19
    • 2019-12-21
    • 2021-05-08
    • 2019-11-03
    • 2019-02-27
    • 2018-02-14
    • 2020-10-13
    • 1970-01-01
    相关资源
    最近更新 更多