iT邦幫忙

2021 iThome 鐵人賽

DAY 25
0
自我挑戰組

Material UI in React系列 第 25

Material UI in React [ Day 25 ] Styles Advanced

今天要講解的內容,在前面講解theme的應用時,有稍微講解了一些基本的應用,官方文件內前半部的內容我就不再提及了,我們會從 Overriding styles 開始講解。

Overriding styles 覆蓋樣式

makeStyles(hook)和 withStyles (HOC) API 允許為每個樣式表創建多個樣式規則,每個樣式規則都有自己的類名,類名通過 classes 變量提供給組件。

// A style sheet
const useStyles = makeStyles({
  root: {}, // a style rule
  label: {}, // a nested style rule
});

function Nested(props) {
  const classes = useStyles();
  return (
    <button className={classes.root}> // 'jss1'
      <span className={classes.label}> // 'jss2'
        nested
      </span>
    </button>
  );
}

function Parent() {
  return <Nested />
}

然而,類名通常是不確定的。父組件如何覆蓋嵌套元素的樣式?

withStyles

包裝的組件接受一個 classes 屬性,它只是合併樣式表提供的類名。

const Nested = withStyles({
  root: {},
  label: {},
})(({ classes }) => (
  <button className={classes.root}>
    <span className={classes.label}> // 'jss2 my-label'
      Nested
    </span>
  </button>
));

function Parent() {
  return <Nested classes={{ label: 'my-label' }} />
}

makeStyles

這個就是前面範例中常用的方法

const useStyles = makeStyles({
  root: {},
  label: {},
});

function Nested(props) {
  const classes = useStyles(props);
  return (
    <button className={classes.root}>
      <span className={classes.label}> // 'jss2 my-label'
        nested
      </span>
    </button>
  );
}

function Parent() {
  return <Nested classes={{ label: 'my-label' }} />
}

String templates

如果你更喜歡 CSS 語法而不是 JSS,您可以使用 jss-plugin-template 插件。

import React from 'react';
import { jssPreset, StylesProvider, makeStyles } from '@material-ui/core/styles';
import { create } from 'jss';
import jssTemplate from 'jss-plugin-template';

const jss = create({
  plugins: [jssTemplate(), ...jssPreset().plugins],
});

const useStyles = makeStyles({
  root: `
    background: linear-gradient(45deg, #fe6b8b 30%, #ff8e53 90%);
    border-radius: 3px;
    font-size: 16px;
    border: 0;
    color: white;
    height: 48px;
    padding: 0 30px;
    box-shadow: 0 3px 5px 2px rgba(255, 105, 135, 0.3);
  `,
});

function Child() {
  const classes = useStyles();
  return (
    <button type="button" className={classes.root}>
      String templates
    </button>
  );
}

function StringTemplates() {
  return (
    <StylesProvider jss={jss}>
      <Child />
    </StylesProvider>
  );
}

export default StringTemplates;

後面都屬 jss 應用的部分,我就不再提及了,因為之後有機會做 JSS 系列的講解時再來補足這部分的應用。

那麼今天的內容就先到這邊了,明天的會講解 API 的部分。


上一篇
Material UI in React [Day 24] Utils 工具組
下一篇
Material UI in React [ Day 26 ] Styles API (part 1)
系列文
Material UI in React30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言