简体   繁体   English

如何使用 Material-UI 按钮在 Typescript function 上实现道具类型?

[英]How to implement prop types on a Typescript function with a Material-UI button?

First of all, my excuses if I'm not expressing myself correctly, I'm still a bit confused with Typescript.首先,我的借口如果我没有正确表达自己,我仍然对Typescript有点困惑。

I have a styled button from Material-UI and I'm not sure how to proceed with making this button reusable throughout the whole app.我有一个来自 Material-UI 的样式按钮,我不确定如何继续使这个按钮在整个应用程序中可重用。 I basically would like the button to receive a prop such as {buttonText} or so, so I can just use it in multiple pages but with different labels.我基本上希望按钮接收一个诸如{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>
  );
}

So when I insert the button component in another page, I could just give a value to the props and then the right label would show on my button.所以当我在另一个页面中插入按钮组件时,我可以给道具一个值,然后正确的 label 会显示在我的按钮上。

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

Any suggestions on how to make this work, using types?关于如何使用类型进行这项工作的任何建议?

Many thanks in advance!提前谢谢了!

First, your component BackButton need to accept props.首先,您的组件 BackButton 需要接受道具。

Then you make a type to props:然后你为 props 做一个类型:

export type BackButtonProps = {
  label: string;
};

And add to your BackButton Component:并添加到您的 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>
  );
}

Now, your BackButton has props which has a type.现在,您的 BackButton 具有具有类型的道具。

Using:使用:

<BackButton label="Custom Label" />

If the library has an internal type to his button, you can extends this type, so your type will have all properties by inheritance:如果库对他的按钮有一个内部类型,您可以扩展此类型,因此您的类型将具有 inheritance 的所有属性:

import { AnyExistingType } from 'material-ui';

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM