reactjs 更改所有Material UI组件的字体系列

xhv8bpkk  于 2023-05-22  发布在  React
关注(0)|答案(8)|浏览(168)

我们能用更少的代码改变Material UI组件的字体系列吗?我已经试过很多方法了,但还是做不到。我不得不单独更改字体家族,这真的是一大堆工作。还有其他方法吗

20jt8wwn

20jt8wwn1#

您可以在material-ui@next库中更改字体,执行以下操作。假设在您的<App />中,其定义如下

// Material UI
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';

const App = () => (
  <MuiThemeProvider theme={THEME}>
    <Provider store={store}>
      <Router history={appHistory} routes={Routes} />
    </Provider>
  </MuiThemeProvider>
 );

 ReactDOM.render(<App />, document.getElementById('app'));

MuiThemeProvidertheme prop中,您提供以下内容,其中

const THEME = createMuiTheme({
   typography: {
    "fontFamily": `"Roboto", "Helvetica", "Arial", sans-serif`,
    "fontSize": 14,
    "fontWeightLight": 300,
    "fontWeightRegular": 400,
    "fontWeightMedium": 500
   }
});

然后在您的css或主index.html文件中的某个位置包含此@import url('https://fonts.googleapis.com/css?family=Roboto:300,400,500,700');
对于所有参数的列表,你可以给予createMuiThemeDefault Theme Params关于文档本身改变MuiTheme,他们如下。Themes Material UI Next
关于<Reboot />部分,您可以在此处查看文档Material UI Reboot Details

o2rvlv0m

o2rvlv0m2#

更新

添加到Adeel接受的答案。
对于最新的Material-UI(v4+)组件,导入以及MuiThemeProvider都已更改。
现在在App.js中,执行以下操作:

import { createMuiTheme } from '@material-ui/core/styles';
import { ThemeProvider } from '@material-ui/styles';
import './Styles/App.css';

const theme = createMuiTheme({
  typography: {
    fontFamily: [
      'Nunito',
      'Roboto',
      '"Helvetica Neue"',
      'Arial',
      'sans-serif'
    ].join(','),
  }
});

class App extends Component {
  render() {
    return (
      <ThemeProvider theme={theme}>
        <div className="App">
          <MainApp />
        </div>
      </ThemeProvider>
    );
  }
}

export default App;

例如,我添加了**Nunito**字体。因此,我必须以以下方式将其添加到App.css(在App.js中导入):

@font-face {
  font-family: 'Nunito';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: local('Nunito Regular'), local('Nunito-Regular'), 
   url(https://fonts.gstatic.com/s/nunito/v11/XRXV3I6Li01BKofINeaBTMnFcQ.woff2) 
   format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, 
    U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, 
    U+2215, U+FEFF, U+FFFD;
}
bxfogqkk

bxfogqkk3#

在MUI v5中,还要确保ThemeProvider和createTheme是从@mui/material/styles而不是从@mui/styles导入的。我花了几个小时思考为什么它不工作。

import { ThemeProvider, createTheme } from '@mui/styles'; ❌

import { ThemeProvider, createTheme } from '@mui/material/styles'; ✅

const theme = createTheme({
  typography: {
    allVariants: {
      fontFamily: 'serif',
      textTransform: 'none',
      fontSize: 16,
    },
  },
});

function App() {
  return (
      <ThemeProvider theme={theme}>
        ...
      </ThemeProvider>
  );
}
oyxsuwqo

oyxsuwqo4#

MUI v5中,您可以轻松更新fontFamily或所有Typography变体的其他CSS属性:

const theme = createTheme({
  typography: {
    allVariants: {
      fontFamily: 'serif',
    },
  },
})

要在应用中动态更改fontFamily,您可以使用useMemo基于最新的fontFamily值创建新的theme对象:

const defaultFontFamily = 'serif';
const [fontFamily, setFontFamily] = React.useState(defaultFontFamily);

const theme = React.useMemo(
  () =>
    createTheme({
      typography: {
        allVariants: { fontFamily },
      },
    }),
  [fontFamily],
);

return (
  <div>
    <Select
      defaultValue={defaultFontFamily}
      onChange={(e) => setFontFamily(e.target.value)}
    >
      <MenuItem value="serif">serif</MenuItem>
      <MenuItem value="sans-serif">sans-serif</MenuItem>
    </Select>
    <ThemeProvider theme={theme}>
      <Content />
    </ThemeProvider>
  </div>
);

现场演示

v6ylcynt

v6ylcynt5#

希望这可以帮助到一些人...在createMuiTheme中声明样式时,需要非常小心逗号和括号。
很容易搞砸的。例如,调色板是一个很大的对象...排版也是如此,确保一切都在正确的位置。我有随机的问题所造成的这样做的错误。

palette: {
    primary: {
      light: '#ff8e8c',
      main: '#ff5a5f',
      dark: '#c62035',
      contrastText: '#fff',
    },
    secondary: {
      light: '#4da9b7',
      main: '#017a87',
      dark: '#004e5a',
      contrastText: '#000',
    },
  },
  typography: {
    allVariants: {
      fontFamily: "'Montserrat', sans-serif",
      textTransform: "none",
    }
    button: {
      textTransform: "none",
    }
  },
kjthegm6

kjthegm66#

这是现在的首选方法:

const theme = createMuiTheme({
  typography: {
    fontFamily: [
      '-apple-system',
      'BlinkMacSystemFont',
      '"Segoe UI"',
      'Roboto',
      '"Helvetica Neue"',
      'Arial',
      'sans-serif',
      '"Apple Color Emoji"',
      '"Segoe UI Emoji"',
      '"Segoe UI Symbol"',
    ].join(','),
  },
});

正如这里所指出的:https://material-ui.com/customization/typography/

w6mmgewl

w6mmgewl7#

这个好像对我有用
GlobalStyleOverrides.js

import { createTheme, responsiveFontSizes } from '@mui/material/styles';

export default function GlobalStyleOverrides() {
  const theme = createTheme({       
    typography: {
      fontFamily: [
        '"Bebas Neue"',
        'Roboto',
        '"Helvetica Neue"',
        'Arial',
        'sans-serif',
      ].join(','),         
      body1: {
        fontFamily: "'Poppins', Arial, sans-serif",
      },
    },
    components: {
      MuiButton: {
        variants: [
          {
            props: { variant: 'contained' },
            style: {
              textTransform: 'none',
              border: `10px dashed red`,
            },
          },              
        ],
      },
    },
  });

  return responsiveFontSizes(theme);
}

App.js

import GlobalStyleOverrides from 'components/_base/global-style-overrides/GlobalStyleOverrides';
...
function App() {
  return (
    <ThemeProvider theme={GlobalStyleOverrides()}>
      <Router>
        ...
      </Router>
    </ThemeProvider>
  );
}
tct7dpnv

tct7dpnv8#

使用中间主题时,将字体放在那里很重要,例如:

import { createTheme } from "@mui/material/styles";
import { Inter } from "next/font/google";

export const inter = Inter({
  subsets: ["latin"],
});

let theme = createTheme({
  typography: {
    allVariants: {
      fontFamily: inter.style.fontFamily,
    },
  },
  breakpoints: {
    values: {
      xs: 0,
      sm: 656,
      md: 1023,
      lg: 1440,
      xl: 1920,
    },
  },
});

const Mytheme = createTheme(theme, {
  typography: {
    h1: {
      fontWeight: 700,
      [theme.breakpoints.between("xs", "md")]: {
        fontSize: "40px",
        lineHeight: "48px",
      },
      [theme.breakpoints.between("md", "xl")]: {
        fontSize: "56px",
        lineHeight: "64px",
      },
    },
    h2: {
      fontWeight: 700,
      fontSize: "40px",
      lineHeight: "48px",
    },
    h3: {
      fontWeight: 700,
      fontSize: "32px",
      lineHeight: "40px",
    },
  },
});

export default Mytheme;

相关问题