[英]How to Override the style of Layout component in React?
<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.