在这里您可以看到在 React 组件之外使用 Material UI 样式的示例。
import React from 'react';
import { makeStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';
const useStyles = makeStyles({
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',
},
});
export default function Hook() {
const classes = useStyles();
return <Button className={classes.root}>Hook</Button>;
}
我想做同样的事情,但在 react 组件内:
class Component extends React.Component {
render() {
const {height} = this.props
const useStyles = makeStyles({
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: height,
padding: '0 30px',
},
});
const classes = useStyles();
return <Button className={classes.root}>Hook</Button>;
}}
可能吗?
我发现这里必须是react with hooks的正确版本,但我没有找到任何人们在类makeStyles
中使用它的示例
最佳答案
makeStyles
创建 React hook ;因此,您无法与类组件进行互操作。
钩子(Hook)用于完全替换类,因为为了编译器优化和其他低级事物,React 更多地朝着纯功能组件的方向发展(尽管对开发人员来说也有外部好处,例如不那么冗长和采取更好地利用 JS 的功能特性并且更直观)。就 makeStyles
而言,您可以获得额外的好处,例如能够使用任何变量,包括传统上的 props 和 state 中的变量,并且 JSS 自动重新计算仅基于您提供的可观察参数与任何 prop 更改时的情况。
相反,正如 @Richard Ansell 指出的那样,您应该使用 withStyles
如果你在课外不舒服。这是High Order Component 。不过,建议您在较新的代码库中学习钩子(Hook)并适应它,因为当您变得更好时,钩子(Hook)可以代表 HOC 和组件的几乎所有功能。
下面是 material-ui
给出的示例文档(RTFM here
):
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';
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',
},
};
function HigherOrderComponent(props) {
const { classes } = props;
return <Button className={classes.root}>Higher-order component</Button>;
}
HigherOrderComponent.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(HigherOrderComponent);
关于reactjs - React组件内的Material ui样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55154172/