首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有办法更改组件中的默认排版?

有没有办法更改组件中的默认排版?
EN

Stack Overflow用户
提问于 2020-01-14 20:47:08
回答 3查看 907关注 0票数 1

Typography component的默认变体和颜色是body1initial。我已经创建了一个组件,当排版组件用作它的子组件时,我希望缺省值为body2textSecondary。有没有办法在Material UI中做到这一点?

代码语言:javascript
复制
<Sidebar>
  <Typography>
    This should have body2 and textSecondary 
    when nothing else is specified.
  </Typography>
</Sidebar>

<Typography>
  This should have the regular defaults.
</Typography>

我当然可以做以下事情,但我真的更喜欢这样一种方式,在子组件中仍然可以使用常规的排版组件。或者,如果有一种方法可以扩展/创建一个替代的排版组件,而不会产生像这样的两个组件(包装器和包装的排版组件)。

代码语言:javascript
复制
import React from 'react';
import Typography, { TypographyProps } from 'components/Typography';

export default function SidebarTypography({
  variant = 'body2',
  color = 'textSecondary',
  ...props
}: TypographyProps): React.ReactElement {
  return <Typography variant={variant} color={color} {...props} />;
}
代码语言:javascript
复制
<Sidebar>
  <SidebarTypography>
    This has body2 and textSecondary.
  </SidebarTypography>
</Sidebar>

<Typography>
  This has the regular defaults.
</Typography>
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-01-16 21:00:16

使用建议的副本(Is it possible to override material-ui components default props?)和“嵌套主题”功能(https://material-ui.com/customization/theming/#nesting-the-theme)的组合解决了我不知道的问题。

代码语言:javascript
复制
const sidebarTheme = (theme) =>
  createMuiTheme({
    ...theme,
    props: {
      ...theme.props,
      MuiTypography: {
        color: 'textSecondary',
        variant: 'body2',
      },
    },
  });

export default function SideBar(props) {
  return (
    <ThemeProvider theme={sideBarTheme}>{props.children}</ThemeProvider>
  );
}
票数 4
EN

Stack Overflow用户

发布于 2020-05-06 11:18:35

您还可以像这样全局覆盖MuiTypography的任何变体。

代码语言:javascript
复制
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';
代码语言:javascript
复制
const theme = createMuiTheme({
  overrides: {
    MuiTypography: {
      body1: {
        fontSize: '18px !important',
        color: 'red',
      },
    },
  },
});
代码语言:javascript
复制
 <MuiThemeProvider theme={theme}> 
        // Your pages...
 </MuiThemeProvider>
票数 1
EN

Stack Overflow用户

发布于 2020-01-14 20:58:18

代码语言:javascript
复制
<Typography variant="h1" component="h2">
  h1. Heading
</Typography>
票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59734094

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档