React JS:应用Material-UI CssBaseline

时间:2018-08-02 16:58:43

标签: css reactjs material-ui

我想使用React为我的新Material-UI应用提供一致的外观。另外,我希望样式等易于维护。因此,默认主题似乎是一个不错的开始。 cssBaseline提供的Material-UI似乎已选中所有复选框,因此我想尝试一下。令人惊讶的是,这没有用。 CSS主题不是我真正的事情。我在这里被误导了吗?以下代码是我在App.js组件中实现的,没有运气(取自here)。我希望只是一个实施细节。

import React from "react";
import Footer from "./Footer";
import CssBaseline from "@material-ui/core/CssBaseline";
import AddTodo from "../containers/AddTodo";
import VisibleTodoList from "../containers/VisibleTodoList";

const App = () => (
  <React.Fragment>
    <CssBaseline />
    <div>
      <AddTodo />
      <VisibleTodoList />
      <Footer />
    </div>
  </React.Fragment>
);

export default App;

编辑:这是位于项目根目录中的index.js

    import React from "react";
    import { render } from "react-dom";
    import { createStore, applyMiddleware } from "redux";
    import { Provider } from "react-redux";
    import App from "./components/App";
    import rootReducer from "./reducers";

    const store = createStore(rootReducer);

   render(
      <Provider store={store}>
        <MuiThemeProvider theme={theme}>
          <React.Fragment>
            <CssBaseline />
            <App />
          </React.Fragment>
        </MuiThemeProvider>
      </Provider>,
      document.getElementById("root")
    );

编辑:我的新App.js

import React from "react";
import Footer from "./Footer";
import AddTodo from "../containers/AddTodo";
import AppBar from "../components/AppBar";
import VisibleTodoList from "../containers/VisibleTodoList";

const App = () => (
  <div>
    <AppBar />
    <AddTodo />
    <VisibleTodoList />
    <Footer />
  </div>
);
export default App;

1 个答案:

答案 0 :(得分:9)

CSSBaseline组件应在Material UI ThemeProvider组件内使用。 在您的示例中,您没有包含ThemeProvider,因此没有Material UI主题。

有关如何设置ThemeProvider的信息,请参见官方文档:https://material-ui.com/customization/themes/#muithemeprovider

基于此示例,使用CSSBaseline的最小工作示例为:

import React from 'react';
import { render } from 'react-dom';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import CssBaseline from "@material-ui/core/CssBaseline";
import Root from './Root';

const theme = createMuiTheme();

function App() {
  return (
    <MuiThemeProvider theme={theme}>
      <React.Fragment>
        <CssBaseline />
        <Root />
      </React.Fragment>
    </MuiThemeProvider>
  );
}

render(<App />, document.querySelector('#app'));

要加载Roboto字体,请将其添加到您的html模板中

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">

有关更完整的示例,请查看此官方示例的源代码:https://github.com/mui-org/material-ui/tree/master/examples/create-react-app/src

  • public / index.html:加载roboto字体
  • src / withRoot.js:ThemeProvider和CSSBaseline设置
  • src / pages / index.js:已应用MUI主题的示例组件