preloader
學習 心得

Adapting style problem when react Use Typescript With Material UI and Emotion

因為在 React web app 自定義 Material-UI button 的樣式時,遇到無法如預期顯示預期的樣式,所以花好多天尋找解決方式: Tag: StylesProvider with injectFirst。定位出這個問題的發生原因之困難在於,釐清這是哪個套件造成的: material-ui or emotion

我的環境是 create-react-app with typescript support 搭建出來的,以下是環境版本:

@emotion/core: 10.0.28
@emotion/styled: 10.0.27
@material-ui/core: 4.9.5
@material-ui/icons: 4.9.1
react: 16.13.0
typescript: 3.7.5

解決方式是:在 web app 的 根節點(root node),通常是 App.tsx 的第一層加上 <StylesProvider injectFirst> 和對應最底下附上</StylesProvider>

原理是:提高套件 material-ui 在 html 檔案的 header 區域動態注入元件的樣式,以降低 css 的優先權。Material-UI 相關文件請點我

以下範例檔使用 typescript, emotion, material-ui 和 react hook 撰寫方式。

/** @jsx jsx */
import { css, jsx } from "@emotion/core";
import { StylesProvider } from "@material-ui/core";

function App() {
  return (
    <StylesProvider injectFirst>
      hello {/* 將原本的元件樹放於此 */}
    </StylesProvider>
  );
}

export default App;