将 TypeScript 与 React 结合使用

介绍

使用TypeScript,我们可以获得IntelliSense的优势,以及关于我们的代码的进一步推理的能力。同样,采用TypeScript是低摩擦的,因为文件可以逐步升级,而不会在整个项目的其余部分引起问题。

前提条件

如果你想跟随这个指南,你将需要:

创建你的项目:

假设您遵循前提指南并安装了 Node.js 和 'npm',请先创建一个新的目录,在这里我们将其称为'react-typescript':

1mkdir react-typescript

在终端中更改到此目录:

1cd react-typescript/

然后初始化一个新的npm项目与默认值:

1npm init -y
 1[secondary_label Output]
 2Wrote to /home/sammy/react-typescript/package.json:
 3
 4{
 5  "name": "react-typescript",
 6  "version": "1.0.0",
 7  "description": "",
 8  "main": "index.js",
 9  "scripts": {
10    "test": "echo \"Error: no test specified\" && exit 1"
11  },
12  "keywords": [],
13  "author": "",
14  "license": "ISC"
15}

在此初始化后,您将安装相应的 React 依赖。

安装 React 依赖

首先,安装 React 依赖 reactreact-dom:

1sudo npm install react react-dom

然后创建一个名为src的文件夹:

1mkdir src

转到这个src目录:

1cd src/

然后创建index.html文件,将其插入到src文件夹中. 您可以使用您喜爱的文本编辑器这样做。

1nano index.html

现在‘index.html’文件已打开,您可以进行一些编辑并添加以下内容:

 1[label index.html]
 2<!DOCTYPE html>
 3<html>
 4<head>
 5  <meta charset="utf-8" />
 6  <meta http-equiv="X-UA-Compatible" content="IE=edge">
 7  <title>React + TypeScript</title>
 8  <meta name="viewport" content="width=device-width, initial-scale=1">
 9</head>
10<body>
11  <div id="main"></div>
12  <script type="module" src="./App.tsx"></script>
13</body>
14</html>

完成后,保存并关闭文件. 如果您使用nano,您可以通过按CTRL + X,然后按YENTER来做到这一点。

我们将使用 Parcel作为我们的包裹,但如果你愿意,你可以选择使用webpack或其他包裹。或者,如果你喜欢使用Create React App,我们先安装Parcel来添加到我们的项目:

1sudo npm install parcel

接下来,安装Typescript:

1sudo npm install --location=global typescript

然后安装 React 和 ReactDOM 类型:

1sudo npm install @types/react @types/react-dom

一旦全部安装完毕,请使用两个期限返回主目录:

1cd ..

启动和运行开发服务器

接下来,更新 package.json 以一个新的任务来启动您的开发服务器. 您可以通过使用您喜爱的文本编辑器创建和打开文件来做到这一点:

1nano package.json

打开文件后,用以下内容替换现有内容:

 1[label package.json]
 2{
 3  "name": "react-typescript",
 4  "version": "1.0.0",
 5  "description": "An example of how to use React and TypeScript with Parcel",
 6  "scripts": {
 7    "dev": "parcel src/index.html"
 8  },
 9  "keywords": [],
10  "author": "Paul Halliday",
11  "license": "MIT"
12}

完成后,保存并关闭文件。

现在,回到src目录:

1cd src/

一旦你在目录中,创建并打开一个包含基本计数的Counter.tsx文件:

1nano Counter.tsx

将以下内容添加到文件中:

 1[label Counter.tsx]
 2import * as React from 'react';
 3
 4export default class Counter extends React.Component {
 5  state = {
 6    count: 0
 7  };
 8
 9  increment = () => {
10    this.setState({
11      count: (this.state.count + 1)
12    });
13  };
14
15  decrement = () => {
16    this.setState({
17      count: (this.state.count - 1)
18    });
19  };
20
21  render () {
22    return (
23      <div>
24        <h1>{this.state.count}</h1>
25        <button onClick={this.increment}>Increment</button>
26        <button onClick={this.decrement}>Decrement</button>
27      </div>
28    );
29  }
30}

完成后,保存并关闭文件。

然后用您喜爱的文本编辑器创建App.tsx文件:

1nano App.tsx

现在文件已打开,添加以下信息来加载计数器:

1[label App.tsx]
2import * as React from 'react';
3import { render } from 'react-dom';
4
5import Counter from './Counter';
6
7render(<Counter />, document.getElementById('main'));

添加内容后,保存并关闭文件。

然后更新您的防火墙权限,以允许1234的端口流量:

1sudo ufw allow 1234

最后,用以下命令运行您的项目:

1sudo npm run dev
1[secondary_label Output]
2
3> [email protected] dev
4> parcel src/index.html
5
6Server running at http://localhost:1234
7✨ Built in 3.84s

通过浏览您的浏览器中浏览 http://your_domain_or_IP_server:1234 来确认一切工作,您应该在您的页面上具有以下增量和减量功能:

Alt text for screen readers

您的样本项目现在已成功启动和运行。

创建 React App 和 TypeScript

如果您更愿意使用 Create React App来启动您的项目,您将很高兴知道CRA现在支持TypeScript(https://facebook.github.io/create-react-app/docs/adding-typescript)。

在召唤create-react-app命令时使用--typescript旗:

功能部件

Stateless 或 功能组件可以在 TypeScript 中定义为:

1import * as React from 'react';
2
3const Count: React.FunctionComponent<{
4  count: number;
5}> = (props) => {
6  return <h1>{props.count}</h1>;
7};
8
9export default Count;

我们正在使用React.FunctionComponent来定义我们的预期代理的对象结构. 在这种情况下,我们预计将被传递到一个名为的单一代理,我们在线中定义它。

1interface Props {
2  count: number;
3}
4
5const Count: React.FunctionComponent<Props> = (props) => {
6  return <h1>{props.count}</h1>;
7};

类组件

类组件可以在 TypeScript 中类似地定义如下:

 1import * as React from 'react';
 2
 3import Count from './Count';
 4
 5interface Props {}
 6
 7interface State {
 8  count: number;
 9};
10
11export default class Counter extends React.Component<Props, State> {
12  state: State = {
13    count: 0
14  };
15
16  increment = () => {
17    this.setState({
18      count: (this.state.count + 1)
19    });
20  };
21
22  decrement = () => {
23    this.setState({
24      count: (this.state.count - 1)
25    });
26  };
27
28  render () {
29    return (
30      <div>
31        <Count count={this.state.count} />
32        <button onClick={this.increment}>Increment</button>
33        <button onClick={this.decrement}>Decrement</button>
34      </div>
35    );
36  }
37}

缺陷普罗普

我们还可以定义DefaultProps在我们可能想要设置默认副本的场景中,我们可以更新我们的计数示例以反映下列情况:

 1import * as React from 'react';
 2
 3interface Props {
 4  count?: number;
 5}
 6
 7export default class Count extends React.Component<Props> {
 8  static defaultProps: Props = {
 9    count: 10
10  };
11
12  render () {
13    return <h1>{this.props.count}</h1>;
14  }
15}

我们还需要停止将this.state.count传入Counter组件,因为这将重写我们的默认支持:

1render () {
2  return (
3    <div>
4      <Count />
5      <button onClick={this.increment}>Increment</button>
6      <button onClick={this.decrement}>Decrement</button>
7    </div>
8  )
9}

您现在应该有一个使用TypeScript和React设置的项目,以及创建您自己的功能和类型组件的工具!

Published At
Categories with 技术
Tagged with
comments powered by Disqus