如何在 React 中覆盖 Layout 组件的样式?

时间:2021-01-27 03:42:52

标签: css reactjs material-ui next.js

  • 我使用 Next.js 和 Material-UI 作为框架。
  • 我有一个 Layout 组件,它使用 Material-UI <Container> 包装内容。
  • 我想覆盖限制背景宽度的 Layout 样式,以便背景扩展到全屏。

components/Layout.js

import { Container } from '@material-ui/core';

export default function Layout({ children }) {
  return <Container>{children}</Container>;
}

pages/_app.js

import Layout from '../components/Layout';

...
<Layout>
  <Component {...pageProps} />
</Layout>
...

pages/index.js

export default function App() {
  return (
    <div style={{ backgroundColor: "yellow" }}>
      Home Page
    </div>
  )
}

example


在大多数情况下使用 Layout 组件会派上用场,但有时我确实想从子组件覆盖某些 Layout 样式。

在这种情况下,如何覆盖对 maxWidth 施加限制的 Layout 组件的样式?

我尝试在 pages/index.js 的样式中添加 {width: '100vw'},但没有成功。

任何帮助将不胜感激。

Link to the SandBox

1 个答案:

答案 0 :(得分:0)

使用 React Context 是我解决此问题的方法。

context/ContainerContext.js

import React from 'react';

const ContainerContext = React.createContext();

export default ContainerContext;

components/Layout.js

import React, { useState } from 'react';
import { Container } from '@material-ui/core';
import ContainerContext from '../context/ContainerContext';

export default function Layout({ children }) {
  const [hasContainer, setHasContainer] = useState(true);

  const Wrapper = hasContainer ? Container : React.Fragment;

  return (
    <ContainerContext.Provider value={{ hasContainer, setHasContainer }}>
      <Wrapper>{children}</Wrapper>
    </ContainerContext.Provider>
  );
}

pages/index.js

import { useContext, useLayoutEffect } from 'react';
import ContainerContext from '../context/ContainerContext';

export default function App() {
  const { setHasContainer } = useContext(ContainerContext);

  // Where the magic happens!
  useLayoutEffect(() => {
    setHasContainer(false);
  }, []);

  return (
    <div style={{ backgroundColor: "yellow" }}>
      Home Page
    </div>
  );
}
相关问题