create-react-app之样式和资产

1.添加样式表

该项目设置使用webpack处理所有资产。webpack提供了一种自定义方式来“扩展” JavaScript以外import的概念。

要表示JavaScript文件依赖于CSS文件,您需要从JavaScript文件导入CSS:

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相比,对其他构建工具和环境的可移植性更差。

在开发中,以这种方式表达依赖关系允许您在编辑样式时即时重新加载样式。在生产中,所有CSS文件都将.css在构建输出中串联为一个缩小的文件。

如果您担心使用特定于Webpack的语义,则可以将所有CSS正确放入src/index.css。它仍然会从中导入src/index.js,但是如果以后迁移到其他构建工具,则始终可以删除该导入。

猜你喜欢

转载自blog.csdn.net/qq_27868061/article/details/112385919