如何仅为Reactjs中的任何组件导入CSS [英] How to import css for only any component in Reactjs

查看:47
本文介绍了如何仅为Reactjs中的任何组件导入CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用React的一个简单项目进行编码.我有2个组件:login,register和2个CSS:login_page,register_page.如何在不覆盖CSS的情况下导入login_page进行登录,register_page进行注册?

I'm coding with small simple project of React. I have 2 components: login, register and 2 css for them: login_page, register_page. How can I import login_page for login, register_page for register without overriding the css?

推荐答案

源- https://codeburst.io/4-four-ways-to-style-react-components-ac6f323da822

import React from 'react';
import registerCSS './register_page.css'; //stylesheet
import loginCSS './login_page.css'; //stylesheet

const DottedBox = () => (
  <div className={registerCSS.container}>
    <p className={loginCSS.content}>Get started with CSS styling</p>
  </div>
);

您的CSS应该是这样

:local(.container) {
   margin: 40px;
   border: 5px dashed pink;
 }
 :local(.content) {
   font-size: 15px;
   text-align: center;
 }

示例

CSS模块是一个CSS文件,默认情况下,所有类名称和动画名称都在本地作用域内.很棒的关于CSS模块的文章.

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. Great article about css modules here.

import React from 'react';
import styles from './DashedBox.css';

const DashedBox = () => (
  <div className={styles.container}>
    <p className={styles.content}>Get started with CSS Modules style</p>
  </div>
);

export default DashedBox;

类似于css,我们导入css文件导入样式'./DashedBox.css'然后我们访问className就像访问对象

Similar to css we import css file import styles './DashedBox.css' then we access to className as we access to object

:local(.container) {
   margin: 40px;
   border: 5px dashed pink;
 }
 :local(.content) {
   font-size: 15px;
   text-align: center;
 }

:local(.className)-由于Webpack配置而使用create-react-app时的此属性.className-如果您使用自己的反应样板,则为this.要使CSS模块与Webpack一起使用,您仅需包括上述模块并将以下加载程序添加到webpack.config.js文件中即可:

:local(.className)-this when you use create-react-app because of webpack configurations .className-this if you use your own react boilerplate. To make CSS modules work with Webpack you only have to include the modules mentioned above and add the following loader to your webpack.config.js file:

. . .
{
  test: /\.css$/,
  loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' 
}
. . .

这篇关于如何仅为Reactjs中的任何组件导入CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆