如何创建一个react类型的应用程序 | 创建-react-app类型的应用程序

150 阅读2分钟

我们有几种方法可以从头开始创建反应式应用程序

  • 使用create-react-app
  • 现有的 react javascript。这篇文章并不涉及如何将现有的react应用转换为typecript。通常情况下,每个开发者都会使用javascript默认编写react组件。

Typescript是javascript的高级版本,具有更多的功能,如严格的类型检查和很多优点。

使用Typescript的React

要求:

  • 已经安装了Node和npm
  • React Javascript、CSS、HTML
  • Visual studio代码编辑器

如何使用Typescript创建一个React应用程序

首先,使用create-react-app CLI工具创建一个反应器

npx create-react-app react-typescript-app --template typescript

这里是一个命令行输出

A:\work>npx create-react-app react-typescript-example --template typescript

Creating a new React app in A:\work\react-typescript-example.

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


added 1369 packages in 7m

169 packages are looking for funding
  run `npm fund` for details

Initialized a git repository.

Installing template dependencies using npm...
npm WARN deprecated source-map-resolve@0.6.0: See https://github.com/lydell/source-map-resolve#deprecated

added 38 packages, and changed 1 package in 41s

169 packages are looking for funding
  run `npm fund` for details

We detected TypeScript in your project (src\App.test.tsx) and created a tsconfig.json file for you.

Your tsconfig.json has been populated with default values.

Removing template package using npm...


removed 1 package, and audited 1407 packages in 9s

169 packages are looking for funding
  run `npm fund` for details

6 moderate severity vulnerabilities

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.

Created git commit.

Success! Created react-typescript-example at A:\work\react-typescript-example
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    , and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd react-typescript-example
  npm start

Happy hacking!

create-react-app默认创建一个react的javascript原型代码库,添加-template typescript,在typecript代码库中创建一个react应用。

进入应用程序文件夹,你可以通过npm start 命令来启动该应用程序。

cd react-typescript-example
npm start

应用服务器已经启动,并在http://localhost:3000/ url上监听。

Typecrip tcomponents

在React中,所有东西都是一个组件。

让我们来讨论一下如何用typescript写一个组件。

在React中,有两种类型的组件

  • 功能性组件,也叫无状态组件
  • 类组件,也叫有状态组件