根 div 填充 React(样式化组件)

问题描述 投票:0回答:5

我有一个简单的 React 应用程序,使用 Redux 的

Provider
来包装我的
App
组件。

import React from 'react';
import ReactDOM from 'react-dom';
import styled from 'styled-components';
import { Provider } from 'react-redux';
import App from './App';
import store from './store';
import registerServiceWorker from './registerServiceWorker';

const MainContainer = styled.div`
  margin: 0;
  padding: 0;
  height: 100vh;
  background-color: red;
`;

ReactDOM.render(
  <MainContainer>
    <Provider store={store}>
      <App />
    </Provider>
  </MainContainer>,
  document.getElementById('root'),
);

registerServiceWorker();

但是,当此应用程序渲染时,屏幕边缘(所有侧面)周围有一个白色间隙。覆盖 body 标签以使

App
内容到达屏幕边缘的正确方法是什么?

css reactjs styled-components
5个回答
8
投票

这是浏览器的默认样式。您可以使用类似 Normalize.css 的东西,或者直接删除正文的边距和填充。

body {
  margin: 0;
  padding: 0;
}

您可以使用

injectGlobal
来完成此操作。

import { injectGlobal } from 'styled-components';

injectGlobal`
  body {
    margin: 0;
    padding: 0;
  }
`;

2
投票

感谢您的答案,但我一直在寻找样式组件的具体答案。

事实证明,Styled Components 有一个辅助方法,

injectGlobal
,它可以覆盖全局 body 标签。

使用它,可以设置所需的属性 - 在本例中,没有边距/填充。因此,将以下内容添加到

index.js
可以解决该问题。

import { injectGlobal } from 'styled-components';

injectGlobal`
  body {
    margin: 0;
    padding: 0;
  }
`;

0
投票

对于

styled components v4
及以后使用
createGlobalStyle
代替:

import { createGlobalStyle } from "styled-components"

const GlobalStyle = createGlobalStyle`
  body {
    color: red;
  }
`

// later in your app's render method
<React.Fragment>
  <Navigation />
  <OtherImportantTopLevelComponentStuff />
  <GlobalStyle />
</React.Fragment>

样式化组件常见问题解答


0
投票

在你的“App.css”中写下:

body {
  overflow-y: hidden;
}

这适用于我的主页。


0
投票
 function App() {
      document.body.style.padding = "0"; // these did the trick
      document.body.style.margin = "0"; // these did the trick

// using App2 because of async not allowed at root level
    
      return <App2></App2>;
    }
© www.soinside.com 2019 - 2024. All rights reserved.