【问题标题】:Style root element using css file, but not working使用css文件样式化根元素,但不工作
【发布时间】:2019-10-05 17:57:50
【问题描述】:

我在reactjs中有入口组件:

import React from "react"
import ReactDOM from 'react-dom';
import App from "./js/components/App.js"
import './index.css';

ReactDOM.render(<App />, document.getElementById('root'));

我正在尝试在我的 css 文件 index.css 中的根元素中设置样式:

  #root {

    background-color: brown;
    height:100vh;
    width:100vh;
  }

虽然背景不是棕色的。在查看浏览器呈现的样式时,我看不到任何这些属性应用于根元素。

这是我的 webpack 配置:

const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader"
          }
        ]
      },
      {
        test: /\.css$/,
        use: ['css-loader'],
      },
    ]
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html"
    })
  ]
};

就好像根本没有加载index.css文件一样。

【问题讨论】:

  • 你应用了两次背景色。
  • 对不起,这是我调试时的一种类型。立即删除

标签: css reactjs webpack


【解决方案1】:

您无法为您的应用设置 #root 样式。只需对&lt;App /&gt; 组件的className 进行样式设置,例如:

const App = () => (
  <div className="app>
  // ...
  </div>
)

css 文件:

.app {
  background-color: #ffffff;
  background-color: brown;
  height:100vh;
  width:100vh;
}

【讨论】:

    【解决方案2】:

    当使用 webpack 时,我认为你必须像这样指定你的 css/js 文件的入口点......

    entry: [
            "./src/js/index.js",
            "./src/sass/style.scss",
        ],
        output: {
            filename: "bundle.js",
            path: path.resolve(__dirname, 'assets/js')
        },
        module: {
            rules: [
    /* you code here */
    ...
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-22
      • 2022-11-16
      • 1970-01-01
      • 2018-07-28
      • 2011-01-20
      • 1970-01-01
      • 2012-10-08
      相关资源
      最近更新 更多