【问题标题】:Is there a fix for styling different components locally?是否有在本地设置不同组件样式的修复程序?
【发布时间】:2021-11-11 03:58:51
【问题描述】:

因此,为了设计我制作的这个新组件的样式,我尝试将其包装在 <div> 中,我尝试过内联样式(这是唯一有效但会变得混乱的样式),我尝试过 css 模块而且我也尝试过配置 webpack.config.js 文件,但似乎没有任何效果。在配置文件中,我无法真正更改它,因为它看起来与 (test: /.css$/,) 不同,这就是它的样子:

{
  test: cssModuleRegex,
  use: getStyleLoaders({
    importLoaders: 1,
    sourceMap: isEnvProduction
      ? shouldUseSourceMap
      : isEnvDevelopment,
    modules: {
      getLocalIdent: getCSSModuleLocalIdent,
    },
  }),
},

由于某种原因,与将样式导入文件有关的任何操作都不起作用。如果我以某种方式使其工作,它仍然会与我的 App.js 组件发生冲突。

博客.css:

h2 {
  font-style: italic;
  color: red;
  font-weight: lighter;
  text-align: center;
  position: relative;
  font-size: 50px;
}

我想在 Blog.js 中设置 h2 标签的样式,但由于某种原因,它总是会与 App.js 发生冲突:

App.js:

import React from "react";
import { Component } from "react";
import fbook from "./image/fbook.png";
import insta from "./image/insta.png";
import tweet from "./image/tweet.png";
import me from "./image/itsme.png";
import Blog from "./components/Blog.js";
import NewWindowComponent from "./NewWindowComponent";




class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isNewWindow: false
    }

    this.handleChange = this.handleChange.bind(this)

    this.handleClick = this.handleClick.bind(this)
  }



  handleChange (event) {
    const {name, value} = event.target
    this.setState({name: value})
  }

  handleClick () {
    this.setState({
      isNewWindow: true
    })
  }



  render() {
    return (
      <body>
        <header>
          <h2>ALEX</h2> //clashes with this h2 tag instead
          <div className='nav'>
            <a href="#">ALL</a>
            <a href="#">TRAVEL</a>
            <a href="#">LIFESTYLE</a>
            <a href="#">MUSIC</a>
            <a href="#">VIDEO</a>
          </div>

          <div className="search-box">
            <input type="text"
              className="search-bar"
              name="stuff"
              onChange={this.handleChange}
              value={this.state.value}
              placeholder="Search"
            />
          </div>
        </header>

        <div id="background">
          <div className= "container">
            <h1>HI! I AM ALEX!</h1><hr/>
            <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            
            <NewWindowComponent
              onClose={this.state.isNewWindow}>
              <Blog />
            </NewWindowComponent>

            <button onClick= {this.handleClick}>GO TO BLOG</button> 
            <img className= "my-pic" src={me} alt="pic of me"/> 
          </div>
        </div>

        <footer>
          <div className="icons">
            <img className ="f-book" src={fbook} alt="Facebook"/>
            <img className ="tweet" src={tweet} alt="Twitter"/>            
            <img className ="insta" src={insta} alt="Instagram"/>
          </div>

          
          <p>© 2021, Designed by not finished </p>
        </footer>
      </body>
    )
  }
}

export default App

NewWindowComponent.js:

import { Component } from "react";
import ReactDOM from 'react-dom';

class NewWindowComponent extends Component {
  containerEl = document.createElement('div');
    
  externalWindow = null;
    
  componentDidMount() {
    this.externalWindow = window.open('', 'NewWindowComponent');
  
    if (this.externalWindow) {
      this.externalWindow
        .document
        .body
        .appendChild(this.containerEl);
      this.externalWindow.onunload = () => this.props.onClose();
      }
    }
  
    render() {
      return ReactDOM.createPortal(this.props.children, this.containerEl);
    }
  }

  export default NewWindowComponent

Blog.js:

import React from "react"
import { Component } from "react";
import "../components/Blog.css";

class Blog extends Component {
    constructor(props) {
        super(props)
        this.state = {
          
        }
       
    }


  render() {
    const myStyle = {
      fontStyle: 'italic',
      fontWeight: 'bold',
      color: 'red',
      textAlign: 'center',
      position: 'relative',
      fontSize: 20
    }

    const scrim = {
      backgroundColor: 'black'
    }

    const woah = {
      lineHeight: 1.5,
      fontSize: 20
    }

    return (
      <body>
        <div className = "cool">
            <header>
                <div style={scrim}className="background">
                <h2>Welcome to my Blog!</h2>
                </div>
            </header>

            <div id="background">
            <div className= "container">
            <h2>About me I guess...</h2><hr/>
            <p style={woah}>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.           </p>
            </div>
            </div>
        </div>
      </body>
    )
  }
}
export default Blog

【问题讨论】:

  • 请完成您问题的第一句话。您能否在codesandbox 或通过 github 链接分享您的完整配置示例?
  • 这里是代码框链接codesandbox.io/s/kptkr 我要做的就是在我的 Blog.js 组件中使用样式表。

标签: javascript css reactjs


【解决方案1】:

CSS 对文档来说是全局的。我想你只需要在 Blog.css 文件中增加 CSS 选择器的特异性。

给定Blog 组件代码:

class Blog extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    const scrim = {
      backgroundColor: "black"
    };

    const woah = {
      lineHeight: 1.5,
      fontSize: 20
    };

    return (
      <body>
        <div className="cool">
          <header>
            <div style={scrim} className="background">
              <h2>Welcome to my Blog!</h2>
            </div>
          </header>

          <div id="background">
            <div className="container">
              <h2>About me I guess...</h2>
              <hr />
              <p style={woah}>
                "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
                enim ad minim veniam, quis nostrud exercitation ullamco laboris
                nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
                in reprehenderit in voluptate velit esse cillum dolore eu fugiat
                nulla pariatur. Excepteur sint occaecat cupidatat non proident,
                sunt in culpa qui officia deserunt mollit anim id est laborum.{" "}
              </p>
            </div>
          </div>
        </div>
      </body>
    );
  }
}

没有

Blogg.css CSS 在这里“泄漏”出来并影响文档的其余部分。

使用更具体的选择器

您可以使用"cool" 类名定位div 的后代元素。

index.css

.App {
  font-family: sans-serif;
  text-align: center;
}

博客.css

.cool h2 {
  font-style: italic;
  color: red;
  font-weight: lighter;
  text-align: center;
  position: relative;
  font-size: 50px;
}

【讨论】:

  • 等等,由于某种原因,我完全复制了你所做的,但它仍然不适用于 Blog.js。它仍然与 App.js 发生冲突 另外,这不是我的 index.css 看起来上面的样子,也许我上次忘记导入这里的“更新”代码:codesandbox.io/s/blog-kptkr Thx 非常感谢您的帮助。
  • @iNfam0usColors 您的新 CSB 似乎崩溃,NewWindowComponent 中出现错误“TypeError: this.props.onClose is not a function”。
  • 很抱歉,如果这不是太麻烦的话,您必须让新标签页保持打开状态,即 NewWindowComponent.js。我试图让按钮单击时,Blog.js 会弹出一个新选项卡。现在我只是尝试设置 Blog.js 的样式,但我尝试的每个解决方案要么最终与 App.js 发生冲突,要么直接不起作用。
  • @iNfam0usColors 我玩过你的沙盒,注释掉一个或另一个,或两者,打开的窗口中的 UI 看起来总是一样的。您能否发布一些屏幕截图,说明它应该是什么样的,以及您目前正在经历什么?很难知道具体要看什么。
  • NewWindowComponent.js 弹出时应该和你上面发送的图片一模一样。 “欢迎到我的博客!”应该居中,红色,字体大小为 20px。这与我遇到的问题相同,我尝试输入的任何样式和打开的窗口(即 Blog.js)都不会改变。上面两张图正是我想要的样子。
猜你喜欢
  • 1970-01-01
  • 2012-01-26
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 2021-03-07
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多