Material-UI样式修改的几种方法

material-UI样式根据项目需求,定制化修改,尝试了几种方法之后,根据应用场景总结以下方法。

一、单个组件,定制化强

  • 定义className,根据每个类,定制化组件样式
  • 行内style,个人不建议使用,因为行内样式权重高、复用性差、后期维护成本高
  • 根据Component API中css部分的api进行较为复杂点样式修改
// 样式
const styles = {
    root: {
        background: 'linear-gradient(45deg, #771cca 30%, #0cb5a5 90%)',
        borderRadius: 3,
        border: 0,
        color: 'white',
        height: 48,
        padding: '0 30px',
        boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    },
    label: {
        textTransform: 'capitalize',
    },
    outlined:{
        border:'5px solid red'
    }
};
// 结构

二、全局样式

// 样式
const theme = createMuiTheme({
    palette: {
        primary: {main: red[500]},
        alarm: {main: blue[500]} // no work
    },
});
// 结构

以上样式代码中,palette中的alarm是自定义属性,出发点是想拓展material-UI原先的theme内容,让所有参数语义化,但是结果并不work,查看material-UI源码,组件只支持api中对应的参数,不支持自定义扩展,故而另寻他法。

三、组件化封装

由于theme自定义参数不起作用,对于想语义化的组件,可以用styles封装自定义的组件,页面上直接引用。

//自定义方法一
import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const styledBy = (property, mapping) => props => mapping[props[property]];

const useStyles = makeStyles({
    root: {
        background: styledBy('color', { //color可自定义其他参数名称
            red: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
            blue: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
        }),
        border: 0,
        borderRadius: 3,
        boxShadow: styledBy('color', {
            red: '0 3px 5px 2px rgba(255, 105, 135, .3)',
            blue: '0 3px 5px 2px rgba(33, 203, 243, .3)',
        }),
        color: 'white',
        height: 48,
        padding: '0 30px',
        '&:hover': {
            background: styledBy('color',{
                red:'blue',
                blue:'red'
            })
        }
    },
});

function MyButton(props) {
    const { color, ...other } = props;
    const classes = useStyles(props);
    return 

附上页面button效果
Material-UI样式修改的几种方法_第1张图片

四、自定义标签、组件

styled-components 自定义标签名、标签样式,不继承material-UI的样式,灵活性强,但个人觉得实用性较低,自定义样式太多,不利于项目页面开展。
// 页面代码如下

import React, {Component} from 'react';
import styled from 'styled-components'

const Wrapper = styled.section`
    margin:0 auto;
    text-align:center;
    width:800px
`
const Button = styled.button`
    width:100px;
    color:red;
    line-height:3rem;
    border:none;
    display:block;
    outline:none;
    border:1px solid red;
    &:hover {
        color:blue
    }
`
const Input = styled.input.attrs({
    type:`password`
})`
    color:red;
    display:block;
    font-size:1rem;
    border:2px solid blue;
    border-radius:5px; 
`
class StylePage extends Component {
    render() {
        return (
        
            
            
        
    )
    }
}

export default StylePage;

页面效果
Material-UI样式修改的几种方法_第2张图片

你可能感兴趣的:(技术)