簡體   English   中英

如何在 React 中覆蓋 Layout 組件的樣式?

[英]How to Override the style of Layout component in React?

  • 我使用 Next.js 和 Material-UI 作為框架。
  • 我有 Layout 組件,它用 Material-UI <Container>包裝內容。
  • 我想覆蓋限制背景寬度的布局樣式,以便背景延伸到全屏。

組件/Layout.js

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

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

頁面/_app.js

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

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

頁面/index.js

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

例子


在大多數情況下使用 Layout 組件會派上用場,但有時我確實想從子組件中覆蓋 Layout 的某些 styles。

在這種情況下,如何覆蓋限制 maxWidth 的 Layout 組件的樣式?

我試圖在 pages/index.js 的樣式中添加{width: '100vw'} ,但沒有奏效。

任何幫助,將不勝感激。

沙盒鏈接

使用React Context是我解決這個問題的方法。

上下文/ContainerContext.js

import React from 'react';

const ContainerContext = React.createContext();

export default ContainerContext;

組件/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>
  );
}

頁面/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>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM