【问题标题】:Tie css file to a component in ReactJs like Angular 2+将 css 文件绑定到 ReactJs 中的组件,如 Angular 2+
【发布时间】:2019-01-24 07:35:39
【问题描述】:

在 Angular 2+ 中,我们有 @component 指令,我们可以在其中传递元素选择器、css 文件、html 模板文件……我们通过以下 sn-p 来完成。

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}

在 Angular 2+ 中,CSS 样式仅在 HomeComponent 元素中是本地的。所以,我可以给不同的组件添加不同的样式,而不会互相影响。

AngularLayout.html

<section>
    <app-home></app-home>
    <app-about></app-about>
    <app-contact></app-contact>
</section>

对于 ReactJs,我尝试为不同的组件添加样式,例如,

LayoutHome.js

import React, { Component } from 'react';
import './LayoutHome.css';

class LayoutHome extends Component {
    render() { return <span>home</span>; }
}

export default LayoutHome;

LayoutAbout.js

import React, { Component } from 'react';
import './LayoutAbout.css';

class LayoutAbout extends Component {
    render() { return <span>about</span>; }
}

export default LayoutAbout;

ReactLayoutApp.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import LayoutHome from './components/LayoutHome';
import LayoutAbout from './components/LayoutAbout';

class App extends Component {
  render() {
    return (
      <section>
        <LayoutHome/>
        <LayoutAbout />
      </section>
    );
  }
}

export default App;

例如,让 './LayoutAbout.css' 具有以下内容

span {
   color: blue;
}

'./LayoutHome.css' 有以下内容

span {
   color: red;
}

CSS 样式正在相互折叠。

在 ReactJs 中将 CSS 文件标记到本地组件的更简洁的方法是什么?

【问题讨论】:

标签: html css angular reactjs separation-of-concerns


【解决方案1】:

您可能应该添加更多的 CSS 选择器。 例如,您的 LayoutAbout.css 看起来像

.about span {
   color: red;
}

还有你的 LayoutHome.css

.home span {
    color: blue;
}

【讨论】:

    【解决方案2】:

    解决此问题的一种方法是在您的 css 中更加具体,以避免冲突,方法是为组件内的外部元素提供类或 id,并在其下嵌套该组件所需的任何样式,如下所示:

    LayoutAbout.js

    import React, { Component } from 'react';
    import './LayoutAbout.css';
    
    class LayoutAbout extends Component {
        render() {
            return (
                <span id="about">
                    about
                    <span>nested content</span>
                </span>
            );
        }
    }
    
    export default LayoutAbout;
    

    LayoutAbout.css

    #about {
        color: blue;
    }
    
    #about span {
        color: dodgerblue;
    }
    

    另一种选择是利用shadow dom,它将您的样式封装在您的自定义组件中。这样可以确保组件中的 css 不会影响外部的任何内容,并且您必须明确影响自定义组件的 shadow dom 内的任何元素。

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      相关资源
      最近更新 更多