【问题标题】:What is the idiomatic way to do styling in Material-UI?在 Material-UI 中进行样式设置的惯用方式是什么?
【发布时间】:2020-06-01 02:23:49
【问题描述】:

有几种方法可以在 Material-UI 中进行样式设置。

  1. 使用makeStyles:
import Box from '@material-ui/core/Box'
const useStyles = makeStyles(theme => ({
  testStyled: (props: isBoolean) => ({
    width: props ? '1px' : '2px',
  })
}))

<Box className={useStyles(true).root}></Box>
  1. 使用MuiBoxProps:
import Box, { MuiBoxProps } from '@material-ui/core/Box'
let isTrue = true
let props: MuiBoxProps  = {
    style: {
        marginBottom: isTrue ? '1px' : '2px'
    }
}
<Box {...props}></Box>

在第二种方式中,我可以为每个单独的组件输入一个特殊的输入。例如:

let props: MuiBoxProps = {
   mb: '1px'
}

类型推断可用于查看编译错误。

但是,此方法不适用于makeStyles,因为它的返回类型始终为CSSProperties

然而,在第一种情况下,我可以通过添加道具在内部设置样式。

所以,总而言之:

  1. 无法对特定组件进行类型推断。可以批量应用道具。

  2. 可以对特定组件进行类型推断。无法批量应用道具。

官方推荐的是什么?

【问题讨论】:

    标签: reactjs styles material-ui


    【解决方案1】:

    实际上,您选择哪种方式并不重要,因为两者都在官方文档中。问题在于您喜欢哪种方法或方式。

    但是是的,我认为最好的方法是withSyles,这也是我在我的专业开发代码中使用的。

    示例如下:

    import React from 'react';
    import PropTypes from 'prop-types';
    import { withStyles } from '@material-ui/core/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);
    

    【讨论】:

      猜你喜欢
      • 2020-08-05
      • 2020-06-11
      • 2021-02-19
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 2018-11-20
      • 2022-08-10
      • 2021-06-02
      相关资源
      最近更新 更多