Html 如何将 CSS 和样式应用到 React 组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38545219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to apply CSS and Styling to a React component
提问by Jake Orben
I have been looking, however, I have had little luck finding any way to style the React.js file that I have created, I converted it from a standard web page, so I have the original CSS, however, I do not know how to use React to display the page with the proper styling.
我一直在寻找,但是,我没有找到任何方法来设置我创建的 React.js 文件的样式,我从标准网页转换它,所以我有原始的 CSS,但是,我不知道如何使用 React 以正确的样式显示页面。
Any help would be appreciated!
任何帮助,将不胜感激!
var NavBar = React.createClass({
render: function() {
return (
/* NavBar */
<div className="dark_bg_color">
<img src="logo.png" />
<div className="table_center">
<div>
<ul>
<li>daily specials</li>
<li>gift gallery</li>
<li>events</li>
<li><i className="fa fa-search" /> search</li>
</ul>
</div>
</div>
<div className="right_nav">
<div className="table_center">
<div>
<button type="button">Sign Up</button>
<button type="button">Log In</button>
<div className="vertical-line"> </div>
<button type="button">Cart</button>
</div>
</div>
</div>
</div>
);
}
});
ReactDOM.render(<NavBar />, document.getElementById('nav'));
var Gallery = React.createClass({
render: function() {
return (
/* Gallery */
<div >
<div align="middle">
<div id="head">
<img id="pic" align="middle" max-width="100%" src="title_pic.png" />
<div align="left" className="big">
<div>
<span>Dine with the Best</span>
<div className="words">
<span>BonApp connects you with limited-time, exclusive meals and events offered by the city's best chefs.<br /><br /><br /><button type="button">JOIN BONAPP</button></span>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
});
ReactDOM.render(<Gallery />, document.getElementById("Gallery"));
var WhatsNew = React.createClass({
render: function() {
return (
<div className="dark_bg_color">
<h2 style={{marginBottom: 30}}>
<span>What's New</span>
</h2>
<div className="autoplay">
<img src="whatsnew0.png" />
<img src="whatsnew1.png" />
<img src="whatsnew0.png" />
</div>
</div>
);
}
});
ReactDOM.render(<WhatsNew />, document.getElementById("whatsnew"));
var BonEvents = React.createClass({
render: function() {
return (
/* Events */
<div id="events" className="dark_bg_color">
<div className="box">
<div className="box-text">
<div className="horizontal-line" />
<div><div className="horizontal-line" /><p>LES BON CADEAUX</p></div>
<div className="horizontal-line" />
</div>
</div>
<h2>
<span>Bon Events</span>
</h2>
<div>
</div>
</div>
);
}
});
ReactDOM.render(<BonEvents />, document.getElementById("events"));
var IOS = React.createClass({
render: function() {
/* IOS */
return (
<div >
<h2>
<span />
</h2>
</div>
);
}
});
ReactDOM.render(<IOS />, document.getElementById("advertiseApp"));
var Footer = React.createClass({
render: function() {
return (
/* Footer */
<div>
<div className="footer_center">
<div>
<ul>
<li>ABOUT</li>
<li>PRESS</li>
<li>CONTACT</li>
<li>SUPPORT</li>
<li>BONAPP FOR RESTAURANTEURS</li>
</ul>
</div>
</div>
<div className="legal_center">
<div>
<ul>
<li>Copyright ? 2016 BonApp Dining Inc.</li>
<li>Privacy Policy</li>
<li>Legal</li>
</ul>
</div>
</div>
</div>
);
}
});
ReactDOM.render(<Footer />, document.getElementById("footer"));
回答by Caleb Anthony
A first read through your question makes it seem that your existing CSS isn't working when you 'React-ify' your webpage.
第一次阅读您的问题会使您的现有 CSS 在您“反应”您的网页时似乎不起作用。
It should.
这应该。
If it's not, there's something else going on that will need further diagnosing to fix. I recently rewrote one of my projects in React and continued to use the exact same CSS file and things worked great.
如果不是,则还有其他事情需要进一步诊断才能解决。我最近在 React 中重写了我的一个项目,并继续使用完全相同的 CSS 文件,并且效果很好。
However, if you're asking about the best wayto go about this...
但是,如果您要问解决此问题的最佳方法......
As others have said, React prefers inline styles.
正如其他人所说,React 更喜欢内联样式。
However, I don't. It's messy, can be difficult to change, and easily gets unwieldy.
但是,我没有。它很乱,很难改变,而且很容易变得笨拙。
SCSS or LESS are the best ways to style in React.
SCSS 或 LESS 是在 React 中设置样式的最佳方式。
But why? Here are a few reasons:
但为什么?以下是几个原因:
Your CSS Is Reusable
你的 CSS 是可重用的
If you style inline with the React way, it works greatfor a couple components.
如果您使用内联方式与方式做出反应,它的工作原理伟大的一对夫妇组件。
But when those components start to stack up, you start realizing you're using the same styles again and again. Which sucks.
但是,当这些组件开始堆积时,您开始意识到自己一次又一次地使用相同的样式。这很糟糕。
It's Easy to Make Changes
很容易做出改变
When a component needs an updated style, you no longer have to dig through your React code to find the right component (or was it the parent component?) and fix it.
当一个组件需要更新样式时,你不再需要通过你的 React 代码来找到正确的组件(或者它是父组件?)并修复它。
Instead, just use CSS like you've always used.
相反,只需像您一直使用的那样使用 CSS。
You Don't Have to Worry About Overwriting
您不必担心覆盖
In the cascading part of CSS, inline styles are the final stop. They overwrite everything.
在 CSS 的级联部分,内联样式是最后一站。它们会覆盖所有内容。
At first, it sounds like a great solution to the styles you're implementing, and in a brochure website, perhaps it would be fine. But when you start working with bigger apps, you run into issues that are almost impossible to troubleshoot.
起初,这听起来像是您正在实施的样式的一个很好的解决方案,在宣传册网站中,也许它会很好。但是当您开始使用更大的应用程序时,您会遇到几乎无法解决的问题。
Instead of fighting with the cascading part of CSS, work with it and keep your styles in the same place.
与其与 CSS 的级联部分作斗争,不如使用它并将您的样式保持在同一位置。
You Use SCSS & LESS Everywhere
您随处使用 SCSS 和 LESS
The biggest point for me is yes, if you're working in React and you prefer inline styles, they can work great.
对我来说最重要的一点是,如果你在 React 中工作并且你更喜欢内联样式,它们可以很好地工作。
But what happens when you move to any other framework? All of a sudden those inline styles don't work so well, and you're back to writing 'normal' CSS with the rest of us. So why change things up just for one framework?
但是当你转向任何其他框架时会发生什么?突然间,那些内联样式不能很好地工作,而您又回到了与我们其他人一起编写“正常”CSS 的状态。那么为什么只为一个框架进行更改呢?
I understand if you work in React full-time and it makes sense to experiment with new best practices, but for most of us, it doesn't make sense to re-invent the wheel when you only can use that wheel on one model of car.
我知道如果你全职在 React 工作并且尝试新的最佳实践是有意义的,但是对于我们大多数人来说,当你只能在一个模型上使用那个轮子时,重新发明轮子是没有意义的车。
回答by adriennetacke
If you want to keep things compartmentalized, you could create a .scss
file for the specific component you are styling then import it in your component file.
如果您想保持分区,您可以.scss
为要设置样式的特定组件创建一个文件,然后将其导入到您的组件文件中。
Example:
示例:
Folder Structure:
文件夹结构:
components
|
|--Card
|
|--Card.js
|--Card.scss
|--index.js
|--Some Other Component Folder
Card.js:
Card.js:
import React, { Component } from 'react';
import classes from './Card.scss';
export class Card extends Component {
render () {
return (
<div className={`${classes.layout} col`}>
<div className={`${classes.card} card`}>
<div className="card-image">
<ProviderImage />
</div>
</div>
</div>
);
}
}
export default Card;
Card.scss:
卡片.scss:
.layout {
img {
display: block;
max-width: 372px;
max-height: 372px;
height: auto;
width: auto;
}
}
.card {
width: 370px;
height: 550px;
}
This keeps the styles contained to its respective component.
这将保留包含在其各自组件中的样式。
回答by Toby
Technically you can add the CSS in the HTML document <head>
as you would with a normal CSS file. So long as your React components have the same classes (except obviously applied as className
no just class
) then it will work.
从技术上讲,您可以<head>
像使用普通 CSS 文件一样在 HTML 文档中添加CSS。只要您的 React 组件具有相同的类(除了明显应用为className
no just class
),它就会起作用。
If you're looking for something more modern and Javascript-oriented, you can look into CSS Modules, and read more about them here:
如果您正在寻找更现代和面向 Javascript 的东西,您可以查看CSS Modules,并在此处阅读有关它们的更多信息:
https://css-tricks.com/css-modules-part-1-need/
https://css-tricks.com/css-modules-part-1-need/
There's obviously a bit more of a learning curve with the second approach though.
不过,第二种方法显然有更多的学习曲线。
回答by Hamms
As Vijay mentioned, React prefers inline styles.
正如 Vijay 提到的,React 更喜欢内联样式。
One common pattern is for each Component to have a single styles
object that contains all the styles used in that Component, like so:
一种常见的模式是每个组件都有一个styles
包含该组件中使用的所有样式的单个对象,如下所示:
var styles = {
navBar: {
backgroundColor: 'dark blue'
},
center: {
textAlign: 'center'
},
rightNav: {
},
verticalLine: {
},
};
var NavBar = React.createClass({
render: function() {
return (
<div style={styles.navBar} >
<img src="logo.png" />
<div style={styles.center} >
<div>
<ul>
<li>daily specials</li>
<li>gift gallery</li>
<li>events</li>
<li><i className="fa fa-search" /> search</li>
</ul>
</div>
</div>
<div style={styles.rightNav}>
<div style={styles.center}>
<div>
<button type="button">Sign Up</button>
<button type="button">Log In</button>
<div style={styles.verticalLine} > </div>
<button type="button">Cart</button>
</div>
</div>
</div>
</div>
);
}
});
回答by Anoop M
Sass will let you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML. Be aware that overly nested rules will result in over-qualified CSS that could prove hard to maintain and is generally considered bad practice. Let me explain with an example.
Sass 可以让你嵌套 CSS 选择器,以遵循 HTML 的相同视觉层次结构。请注意,过度嵌套的规则将导致过度限定的 CSS,这可能难以维护,并且通常被认为是不好的做法。让我用一个例子来解释。
Hero.jsx
英雄.jsx
import "./Hero.scss";
import React, { Component } from "react";
class Hero extends Component {
render() {
return (
<div className="hero-component">
<span className="hero-header">Scss is awsome.</span>
</div>
);
}
}
export default Hero;
Hero.scss
英雄.scss
.hero-component {
.hero-header {
<!-- Hero header style goes here -->
}
.other-class {}
}
回答by Vinicius Vieira
I think first of all you need to import your css or scss files, i recommend doing it to the direct path like:
我认为首先您需要导入您的 css 或 scss 文件,我建议将其导入到直接路径中,例如:
import "components/card/card";
In order for this to work you need to have SASS loaders and webpack running in your project.
为了让它工作,你需要在你的项目中运行 SASS 加载器和 webpack。
You need to have sass loaders in your webpack.config
您需要在 webpack.config 中有 sass 加载器
module: {
loaders: [
{test: /\.scss$/, loaders: ["style", "css", "sass"]},
{test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader")},
{test : /\.woff|\.woff2|\.svg|.eot|\.ttf|\.png/, loader : 'url?prefix=font/&limit=10000&name=/assets/fonts/[name].[ext]'
}
]
I recoomed use the "sass-loader": "^3.0.0",
我重新使用 "sass-loader": "^3.0.0",
The loader needs a workaround to work with windows, on mac it works fine:
加载程序需要一种解决方法来处理 Windows,在 mac 上它工作正常:
Display hidden files on folder option.
Go to the folder 'user/appData', it should be on: C:\Users\user\AppData\Roaming\npm
Add the windows enviroment variable:NODE_PATH C:\Users\user\AppData\Roaming\npm\nodeModules
Run the command npm install -g
Close and reopen the command prompt.
在文件夹选项上显示隐藏文件。
转到文件夹“user/appData”,它应该在:C:\Users\user\AppData\Roaming\npm
添加windows环境变量:NODE_PATH C:\Users\user\AppData\Roaming\npm\nodeModules
运行命令 npm install -g
关闭并重新打开命令提示符。
With this you can load sass and compile it with webpack, and I do recomend using it with react, it's really powerfull.
有了这个,你可以加载 sass 并用 webpack 编译它,我确实建议将它与 react 一起使用,它真的很强大。
If your not usng webpack you can find more here: http://webpack.github.io/docs/tutorials/getting-started/
如果你不使用 webpack,你可以在这里找到更多:http://webpack.github.io/docs/tutorials/getting-started/
And here you can check and example of webpack build process: Why is my webpack bundle.js and vendor.bundle.js so incredibly big?
在这里您可以查看 webpack 构建过程的示例:为什么我的 webpack bundle.js 和 vendor.bundle.js 如此之大?
回答by Maria Campbell
I use Sass (.scss)
to style my React components. I have also used PostCSS. And they are also modularized. Once you have it set up via your workflow (I use webpack), all you need to do to style your React app is to import the style.scss
(yes, .scss
) which contains your imported partials etc into your index.js
file which resides in root along with your main App.js
. That's where everything else you need in order to make your app work resides as well. For example, this is what mine looks like for the React app I am working on now:
我使用 Sass(.scss)
来设计我的 React 组件。我也使用过 PostCSS。而且它们也是模块化的。一旦你通过你的工作流程(我使用 webpack)设置了它,你需要做的就是为你的 React 应用程序设置样式style.scss
,.scss
将包含你导入的部分等的(yes, ) 导入到你的index.js
文件中,该文件与你的主文件一起位于根目录中App.js
. 这也是使您的应用程序正常工作所需的一切。例如,这就是我现在正在开发的 React 应用程序的样子:
Index.js:
索引.js:
import React from 'react';
import ReactDOM from 'react-dom';
import 'core-js/es6/map';
import 'core-js/es6/set';
import App from './App';
import './favicon.ico';
import './style/style.scss';
ReactDOM.render(
<App />, document.getElementById('root')
);