programing

모든 MUI 구성 요소의 글꼴 패밀리 변경

sourcejob 2023. 3. 25. 11:04
반응형

모든 MUI 구성 요소의 글꼴 패밀리 변경

코드 수가 적은 MUI 컴포넌트의 폰트 패밀리를 변경할 수 있습니까?여러 가지 방법을 시도해 봤지만 여전히 할 수 없어요.폰트 패밀리를 개별적으로 변경해야 하기 때문에 많은 작업이 필요합니다.다른 방법은 없나요?

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'));

에서theme을 지지하다.MuiThemeProvider다음과 같은 기능을 제공합니다.

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');

모든 매개 변수 목록을 보려면createMuiTheme 디폴트 테마 파라미터MuiTheme 변경에 관한 문서 자체에 대해서는 다음과 같습니다.테마 머티리얼 UI 다음

에 대해서<Reboot />부품 머티리얼 UI 재부팅 세부 정보에서 설명서를 볼 수 있습니다.

*** 업데이트 ******

아델이 수락한 답변에 추가.

최신 Material-UI(v4+) 컴포넌트의 경우 Import 및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;

예를 들어 글꼴을 추가했습니다.그래서 나는 같은 것을 더해야 했다.App.css(이것들은 Import되고 있습니다.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;
}

MUI v5에서는 TemeProvider를 확인하고테마를 가져온 위치@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>
  );
}

MUI v5 에서는, 다음의 정보를 갱신할 수 있습니다.fontFamily또는 기타 모든 CSS 속성Typography쉽게 변형할 수 있습니다.

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

를 변경하려면fontFamily어플리케이션에서 동적으로useMemo새로 만들다theme최신 정보를 바탕으로 한 오브젝트fontFamily값:

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>
);

라이브 데모

Codesandbox 데모

이게 누군가에게 도움이 되길 바라면서...당신은 당신의 스타일을 선언할 때 쉼표와 괄호를 매우 조심해야 합니다.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",
    }
  },

현재 권장되는 방법은 다음과 같습니다.

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/

이건 나한테 효과가 있는 것 같아

Global Style Overrides.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>
  );
}

언급URL : https://stackoverflow.com/questions/48319372/changing-font-family-of-all-mui-components

반응형