[英]How to override (overwrite) classes and styles in material-ui (React)
我正在使用material-ui的 1.2.1 版,我正在嘗試覆蓋AppBar組件以使其透明。 該文檔概述了如何在此處覆蓋 styles。
我的代碼:
import React, { Component } from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import logo from '../Assets/logo.svg';
class NavigationBar extends Component {
render() {
const styles = {
root: {
backgroundColor: 'transparent',
boxShadow: 'none',
},
};
return (
<AppBar position={this.props.position} classes={{ root: styles.root }}>
<Toolbar>
<img src={logo} style={{ height: '28px' }} />
</Toolbar>
</AppBar>
);
}
}
export default NavigationBar;
但這不會產生任何結果。 我是否試圖覆蓋錯誤? 不知道我哪里錯了...
這個答案使@Nadun 的答案變得完整——他值得稱贊。 要覆蓋材質 ui 類,我們需要了解以下內容:
1. 在頂部的 const 變量中添加樣式
const styles = {
root: {
backgroundColor: 'transparent !important',
boxShadow: 'none',
paddingTop: '25px',
color: '#FFFFFF'
}
};
2.我們需要使用帶有“withStyles”的高階函數來覆蓋材質ui類
export default withStyles(styles)(NavigationBar);
3.現在這些樣式可以作為渲染函數中的道具使用,嘗試這樣做 - console.log(this.props.classes)
- 你會得到一個類名,對應於你包含在樣式對象中的屬性,比如 - {root: "Instructions-root-101"}
.
添加類屬性
render() {
const { classes } = this.props;
return (
<AppBar classes={{ root: classes.root }}>
// Add other code here
</AppBar>
)
}
import React, { Component } from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import logo from '../Assets/logo.svg';
import { withStyles } from '@material-ui/core/styles';
const styles = {
transparentBar: {
backgroundColor: 'transparent !important',
boxShadow: 'none',
paddingTop: '25px',
color: '#FFFFFF'
}
};
class NavigationBar extends Component {
render() {
return (
<AppBar className={classes.transparentBar}>
<Toolbar>
<img src={logo} style={{ height: '28px' }} />
</Toolbar>
</AppBar>
);
}
}
export default withStyles(styles)(NavigationBar);
找到重要的部分:
backgroundColor: 'transparent !important'
有關更多詳細信息,請參閱本指南: https : //material-ui.com/customization/overrides/
希望能幫到你
paper: {
margin: spacing(7),
"&>ul": {
...
},
},
添加到上面的答案中,如果您想為某些內部自動生成的元素添加樣式,則可以使用此語法執行此操作
<TextField className={classes.txtField}
然后在類對象中,我們可以通過這種方式來處理存在於 TextField 中的標簽
const useStyles = makeStyles((theme) => ({
txtField: {
"& label": {
padding: 23
}
}
});
import ...;
import { withStyles } from '@mui/styles';
const styles = {
transparentBar: {
backgroundColor: 'transparent !important',
boxShadow: 'none',
paddingTop: '25px',
color: '#FFFFFF'
}
};
function NavigationBar (props) {
const { classes } = props;
return (
<AppBar className={classes.transparentBar}>
<Toolbar>
<img src={logo} style={{ height: '28px' }} />
</Toolbar>
</AppBar>
);
}
export default withStyles(styles)(NavigationBar);
這個對我有用。
筆記!更新 MUI 核心版本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.