如何将Material UI v4自定义Button的HOC示例转换为TypeScript类组件
MUI v4 TypeScript类组件自定义按钮实现方案
完整实现代码
import React, { Component } from 'react'; import { Button, withStyles, WithStyles, ButtonProps } from '@material-ui/core'; // 样式定义和官方示例完全一致 const styles = { root: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, padding: '0 30px', }, }; // 定义组件Props类型 // 继承WithStyles获得classes的自动类型推导,继承ButtonProps获得按钮所有原生属性支持 interface CustomButtonProps extends WithStyles<typeof styles>, ButtonProps {} class CustomButton extends Component<CustomButtonProps> { render() { // 解构出classes,剩余props透传给Button组件 const { classes, ...rest } = this.props; return <Button className={classes.root} {...rest} />; } } // 用withStyles包裹类组件导出,用法和函数组件完全一致 export default withStyles(styles)(CustomButton);
组件使用示例
// 在其他组件中直接导入使用即可 <CustomButton onClick={() => alert('点击触发')}> 自定义按钮 </CustomButton>
关键说明
WithStyles是MUI v4提供的内置工具类型,会自动根据你定义的styles对象推导classes的属性类型,无需手动声明classes接口- 如果不需要支持Button的所有原生属性,可以去掉Props继承的
ButtonProps,只保留自己需要的自定义属性即可 withStyles作为高阶组件,包装类组件的用法和包装函数组件没有差异
内容的提问来源于stack exchange,提问作者user11727302
相关产品推荐
相关产品推荐

