创建React应用程序的教程

80 阅读5分钟

Create React App是一个很好的工具,可以让你快速地使用React.js。前端开发是很复杂的,有很多构建工具,你的头会旋转。Create React App将所有这些复杂的东西变得简单。你所需要做的就是用npm安装软件包,然后运行几个简单的命令就可以创建一个新的项目并开始运行。Create React App使用Webpack、Babel、ESLint和其他奇妙的项目来支持你的新应用。如果你想修补详细的配置,你可以从Create React App中 "弹出",直接编辑他们的配置文件。让我们来看看如何设置Create React App和Visual Studio Code以获得一些编码的乐趣。


为React开发设置Visual Studio Code

首先,由于我们将在这一轮React教程中使用Visual Studio Code,让我们安装和配置一些扩展,使事情变得更容易。第一个要安装的扩展是Prettier
Prettier formatter for Visual Studio Code

Prettier会重新格式化你的代码,使其更漂亮。谁不想要漂亮的代码呢?奖励:这个扩展能够格式化我们在React中使用的JSX标记。接下来,我们可以安装Simple React Snippets扩展,它为我们提供了一些很棒的快捷方式来快速设置React中的类或函数组件。
Simple React Snippets

下面是这些快捷方式和它们的作用。

短语渲染
imr导入React
imrc导入React/组件
impt导入PropTypes
impc导入React / PureComponent
cc组件类
ccc带有构造函数的类组件
sfc无状态函数组件
cdmcomponentDidMount
cwm将要安装的组件
cwrp组件将接收道具
gds从道具中获取衍生状态(getDerivedStateFromProps
scu应更新的组件(shouldComponentUpdate
cwucomponentWillUpdate
cdu组件已更新
cwu组件将更新
cdc组件已捕获
gsbugetSnapshotBeforeUpdate
ss设置状态
ssf功能性设置状态
渲染渲染
rprop渲染道具
统一高阶组件

创建一个React应用程序

在React的介绍中,我们使用Create React App工具来快速建立一个React应用。我们现在要再次使用这个工具来创建一个新的应用程序。

react $create-react-app reactable
Creating a new React app in C:nodereactreactable.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

如果一切顺利,安装完成后,你应该看到类似这样的东西。
npm create-react-app

好了,把这个问题解决了,我们来启动应用程序。

react $cd reactable
reactable $npm start

当服务器启动时,它将为你自动启动一个浏览器窗口,并加[载http://localhost:3000/,该窗口将显示React应用程序的欢迎闪动页面。
React_App_-_Google_Chrome

现在,我们可以打开包含react应用程序的文件夹。在我们的例子中,我们称它为reactable,所以我们打开这个文件夹。
react application folder structure

在react应用程序根目录下有几个文件和文件夹。其中一些如下。

  • node_modules包含 React 库和任何其他需要的第三方库。
  • public存放应用程序的公共资产。这是index.html文件所在的地方,React将默认在
    元素上装载应用程序。
  • src包含 App.css、App.js、App.test.js、index.css、index.js、logo.svg 和 serviceWorker.js 文件。App.js文件负责显示React中的默认欢迎界面。
  • package-lock.json在任何npm修改node_modules树或package.json的操作中自动生成。
  • package.json保存了与项目相关的各种元数据。这个文件用于向 npm 提供信息,使其能够识别项目并处理项目的依赖关系。
  • README.md你需要阅读它来了解。

JSX简介

现在我们可以打开App.js文件,看一下里面的内容。

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit src/App.js and save to reload.
          </p>
          <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer">
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;

在上面的代码中,有几件事情正在发生。首先,我们可以看到,一个ES6类被用来创建一个组件。在这个类中有一个 render()方法。在这个方法中,我们返回高亮的标记。所以这部分看起来有点古怪。JavaScript里的HTML?嗯,这种标记并不是真正的JavaScript或HTML,而是一种特殊的标记类型,被称为JSX,或JavaScript XML。为了使JSX能够发挥作用,它需要通过一个被称为Babel的编译器。Babel所做的是将JSX的语法转换成任何浏览器都能理解的普通JavaScript代码。作为一个例子,我们手动将上面突出显示的代码通过Babel运行,这是生成的JavaScript代码。

("use strict");

React.createElement(
  "div",
  {
    className: "App"
  },
  React.createElement(
    "header",
    {
      className: "App-header"
    },
    React.createElement("img", {
      src: logo,
      className: "App-logo",
      alt: "logo"
    }),
    React.createElement(
      "p",
      null,
      "Edit ",
      React.createElement("code", null, "src/App.js"),
      " and save to reload."
    ),
    React.createElement(
      "a",
      {
        className: "App-link",
        href: "https://reactjs.org",
        target: "_blank",
        rel: "noopener noreferrer"
      },
      "Learn React"
    )
  )
);

所以你可以看到,在React中创建元素的方式是通过React.createElement()函数。大多数人宁愿写JJSX标记而不是相应的JavaScript代码。使用JSX来描述用户界面应该是什么样子,肯定比手动写出所有这些对**React.createElement()**的调用要简单。

我们也有App.css文件,如我们所见,它被导入到App.js文件中。
app-css for create react app

App.css使用这些css代码来设计主要的App组件。

.App {
  text-align: center;
}

.App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 40vmin;
  pointer-events: none;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

App.test.js

这个文件有一些代码可以让你开始在React中进行测试。

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});

index.css

index.css文件用于全局的css样式设计。

body {
  margin: 0;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
    monospace;
}

index.js

index.js文件是React应用程序的入口点。

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

logo.svg

logo.svg文件有App组件的SVG图形。


serviceWorker.js

这是用来创建[渐进式Web应用]的。


尝试没有构建步骤的React

尽管Create React App让你相当快速和容易地开始使用React,但也许你只是想把它放到一个HTML页面中,然后就开始了。事实证明这也是可行的,你可以简单地下载这个html文件,或者复制下面列出的内容,你就可以在一个HTML文件中开始使用react。如果你只是想踢一下轮胎,了解一下React的工作原理,那绝对值得一试。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      ReactDOM.render(<h1>Hello, world!</h1>, document.getElementById("root"));
    </script>
    <!--
      Note: this page is a great way to try React but it's not suitable for production.
      It slowly compiles JSX with Babel in the browser and uses a large development build of React.

      Read this section for a production-ready setup with JSX:
      https://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project

      In a larger project, you can use an integrated toolchain that includes JSX instead:
      https://reactjs.org/docs/create-a-new-react-app.html

      You can also use React without JSX, in which case you can remove Babel:
      https://reactjs.org/docs/react-without-jsx.html
    -->
  </body>
</html>

创建React应用程序教程摘要

通过本教程,我们现在已经准备好开始使用React来开发一些前端应用程序了。在接下来的教程中,我们将这样做。