reactjs - 如何使用 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>
关于如何使用类型进行这项工作的任何建议?
提前谢谢了!
解决方案
首先,您的组件 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 };
推荐阅读
- c++ - 如何将位图文件切成相等的部分并将每个部分保存在一个新的位图文件中?
- kotlin - 天气休息 api 的 URL 操作
- visual-studio-code - 节点调试 - 断点显示在只读文件中
- java - jar 文件是否不包含导入的包和类?
- html - 动画不会在半秒帧立即结束
- php - 在 Codeigniter 4 中添加 mysqli 选项
- docker - WSL2 上的 Docker 卷
- java - 在java中将int数组转换为不带逗号的字符串
- machine-learning - 'DataFrame' 对象没有属性 'convert_objects'
- python - 如果我启动程序就会退出,你能帮我吗?