Skip to main content

添加样式表

此项目设置使用 webpack 来处理所有资源。webpack 提供了一种将 import 的概念“扩展”到 JavaScript 之外的自定义方式。为了表达 JavaScript 文件依赖于 CSS 文件,你需要从 JavaScript 文件导入 CSS:

¥This project setup uses webpack for handling all assets. webpack offers a custom way of “extending” the concept of import beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to import the CSS from the JavaScript file:

Button.css

.Button {
padding: 20px;
}

Button.js

import React, { Component } from 'react';
import './Button.css'; // Tell webpack that Button.js uses these styles

class Button extends Component {
render() {
// You can use them as regular CSS styles
return <div className="Button" />;
}
}

这对于 React 来说不是必需的,但很多人发现这个功能很方便。你可以 此处 阅读此方法的好处。但是,你应该意识到,与 webpack 相比,这会降低你的代码对其他构建工具和环境的可移植性。

¥This is not required for React but many people find this feature convenient. You can read about the benefits of this approach here. However you should be aware that this makes your code less portable to other build tools and environments than webpack.

在开发中,以这种方式表达依赖允许你的样式在你编辑它们时即时重新加载。在生产中,所有 CSS 文件将在构建输出中连接成一个压缩的 .css 文件。

¥In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified .css file in the build output.

如果你担心使用特定于 webpack 的语义,你可以将所有 CSS 直接放入 src/index.css。它仍然会从 src/index.js 导入,但如果你稍后迁移到不同的构建工具,你始终可以删除该导入。

¥If you are concerned about using webpack-specific semantics, you can put all your CSS right into src/index.css. It would still be imported from src/index.js, but you could always remove that import if you later migrate to a different build tool.