Open7

MaterialUIのTheme

みつよしみつよし

知りたいこと

補足

  • リアルタイムの変更は考えていない
みつよしみつよし
  • Themeをカスタマイズする場合は ThemeProvider を使う
  • ThemeProvider はReactのインターフェースに適合しており、カスタムThemeを適用したいコンポーネントの親に ThemeProvider を設定する必要がある
  • 子エレメントからThemeを使うには useTheme を経由する

If you wish to customize the theme, you need to use the ThemeProvider component in order to inject a theme into your application. However, this is optional; Material-UI components come with a default theme.

ThemeProvider relies on the context feature of React to pass the theme down to the components, so you need to make sure that ThemeProvider is a parent of the components you are trying to customize. You can learn more about this in the API section.
https://material-ui.com/customization/theming/

みつよしみつよし

カスタムThemeの生成

デフォルトThemeを一部変更する場合

createMuiTheme を利用する

import { createMuiTheme } from '@material-ui/core/styles';
import purple from '@material-ui/core/colors/purple';
import green from '@material-ui/core/colors/green';

const theme = createMuiTheme({
palette: {
primary: {
main: purple[500],
},
secondary: {
main: green[500],
},
},
});
https://material-ui.com/customization/theming/

0から作る場合

import { ThemeProvider } from '@material-ui/core/styles';
import DeepChild from './my_components/DeepChild';

const theme = {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
};

function Theming() {
return (
<ThemeProvider theme={theme}>
<DeepChild />
</ThemeProvider>
);
}
https://material-ui.com/styles/advanced/

みつよしみつよし

Themeがコンポーネントに与える影響

コンポーネントのAPI Docsの implementation of the component for more detail. からソースを読む

みつよしみつよし

テキスト(p element)にthemeを適用するには

  • a) themeを通常のCSSに変換してpに適用する
  • b) pではなくMaterialUIのコンポーネントを用いる

themeを通常のCSSに変換してpに適用する

withStyles を使用する?
クラス経由で指定するようだがよくわからず
https://stackoverflow.com/a/52928440

pではなくMaterialUIのコンポーネントを用いる

Typographyparagraph=true を設定すれば内部的にpになるが、themeのfontFamilyを読み込んでいない
https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/Typography/Typography.js