使用Create React App v2和TypeScript

news/2024/7/4 8:35:41

介绍 (Introduction)

Create React App v2 introduced official TypeScript support, allowing JavaScript users to use TypeScript with the React front-end framework. TypeScript is a powerful tool that helps write safer, self-documenting code, allowing developers to catch bugs faster.

Create React App v2引入了官方TypeScript支持,从而允许JavaScript用户将TypeScript与React前端框架一起使用。 TypeScript是一个功能强大的工具,可帮助编写更安全的自文档代码,使开发人员可以更快地发现错误。

For this article, you will go through the steps of creating a React app with TypeScript using Create React App.

对于本文,您将完成使用Create React App使用TypeScript创建React应用的步骤。

启动TypeScript创建React应用 (Starting a TypeScript Create React App)

First, let’s use create-react-app with the --typescript flag.

首先,让我们使用带有--typescript标志的create-react-app

  • npx create-react-app my-typescript-app --typescript

    npx create-react-app my-typescript-app --typescript

Let’s look at what packages the --typescript flag get us and what changes it makes.

让我们看一下--typescript标志为我们提供了哪些软件包以及它进行了哪些更改。

TypeScript附加项 (The TypeScript Additions)

The --typescript flag will add the main TypeScript package.

--typescript标志将添加主TypeScript包 。

We also get this notice: We detected TypeScript in your project (src/App.test.tsx) and created a tsconfig.json file for you.

我们还会收到此通知: We detected TypeScript in your project (src/App.test.tsx) and created a tsconfig.json file for you.

The tsconfig.json file is how we configure TypeScript projects, similar to how package.json is for JS projects.

tsconfig.json文件是配置TypeScript项目的方式,类似于package.json用于JS项目的方式。

The default tsconfig.json will look something like the following:

默认的tsconfig.json如下所示:

{
  "compilerOptions": {
    "target": "es5",
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": ["src"]
}

检查App.tsx文件 (Examining the App.tsx File)

Let’s jump into the main App file that usually is our main React component:

让我们进入通常是我们主要的React组件的主要App文件:

app.tsx
app.tsx
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 <code>src/App.tsx</code> 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;

As you will notice, this is actually the same as the JavaScript App.js. We get the same base as our JavaScript projects, but we can sprinkle TypeScript on top.

您将注意到,这实际上与JavaScript App.js相同。 我们拥有与JavaScript项目相同的基础,但是我们可以将TypeScript撒在上面。

Next, let’s create a TypeScript component and see what benefits we can gain.

接下来,让我们创建一个TypeScript组件,看看我们可以获得什么好处。

创建一个TypeScript组件 (Creating a TypeScript Component)

We’ll start by creating a normal functional component in this same App.tsx file:

我们将从在相同的App.tsx文件中创建普通功能组件开始:

function MyMessage({ message }) {
  return <div>i shall speak! my message is: {message}</div>;
}

This is a simple component where we pull message out of props. Now let’s add some TypeScript to tell this function that its message parameter should be a string.

这是一个简单的组件,我们从props提取message 。 现在,让我们添加一些TypeScript来告诉该函数其message参数应该为string

If you’re familiar with TypeScript, you may think you want to add the following to message: message: string. What we have to do in this situation is define the types for all props as an object. There’s a few ways we can do this:

如果您熟悉TypeScript,您可能会想将以下内容添加到message: message: string 。 在这种情况下,我们要做的就是将所有props的类型定义为一个对象。 我们有几种方法可以做到这一点:

Types inline:

内联类型:

function MyMessage({ message }: { message: string }) {
  return <div>i shall speak! my message is: {message}</div>;
}

Props object:

道具对象:

function MyMessage(props: { message: string }) {
  return <div>i shall speak! my message is: {props.message}</div>;
}

Separate types object:

单独的类型对象:

interface MyMessageProps {
  message: string;
}

function MyMessage({ message }: MyMessageProps) {
  return <div>i shall speak! my message is: {props.message}</div>;
}

There are many ways to use TypeScript in our projects. You can create an interface and move that into a separate file so your types can live elsewhere. This may seem like a lot of writing, so let’s see what we gain from writing a bit more.

在我们的项目中有多种使用TypeScript的方法。 您可以创建一个interface并将其移到一个单独的文件中,以便您的类型可以放在其他地方。 这看起来好像是很多写作,所以让我们看看从多写一点中我们会得到什么。

We’ve told this component that it only accepts a string as the message parameter. Now let’s try using this inside our App component.

我们已经告诉该组件它仅接受string作为message参数。 现在,让我们尝试在我们的App组件中使用它。

使用TypeScript组件 (Using TypeScript Components)

Let’s use this MyMessage component.

让我们使用这个MyMessage组件。

When we go to use this component, we can see VS Code bring up the component’s signature right as we type. We don’t have to jump back to the component (especially if it’s in another file) to see what its inputs should be.

当我们使用该组件时,我们可以看到VS Code在键入时显示出该组件的签名。 我们不必跳回到组件(尤其是如果它在另一个文件中)来查看其输入内容。

That isn’t the most readable, so let’s jump into using each prop individually.

那不是最易读的,所以让我们跳入每个道具的单独使用。

查看道具类型 (Seeing Prop Types)

As soon as we start typing message, we can see what that prop should be:

一旦开始键入message ,我们就可以看到该道具应该是:

看到类型错误 (Seeing Type Errors)

If we add a number as a message, TypeScript will throw an error and help us catch these typing bugs.

如果我们在消息中添加数字,TypeScript将引发错误并帮助我们捕获这些键入错误。

React won’t even compile if there are type errors like this:

如果存在如下类型错误,React甚至不会编译:

结论 (Conclusion)

This only scratches the surface of what TypeScript provides us. You can create types for all your components and props, and with VS Code you’ll be able to read them. You’ll also catch errors faster since TypeScript won’t even let the project compile with type errors.

这只是TypeScript为我们提供的内容的起点。 您可以为所有组件和道具创建类型,使用VS Code,您将能够阅读它们。 由于TypeScript甚至不会让项目编译时遇到类型错误,因此您还将更快地捕获错误。

翻译自: https://www.digitalocean.com/community/tutorials/using-create-react-app-v2-and-typescript


http://www.niftyadmin.cn/n/3649266.html

相关文章

6个值得推荐的Android开源框架简介

1、volley 项目地址 https://github.com/smanikandan14/Volley-demo (1) JSON&#xff0c;图像等的异步下载&#xff1b; (2) 网络请求的排序&#xff08;scheduling&#xff09; (3) 网络请求的优先级处理 (4) 缓存 (5) 多级别取消请求 (6) 和Activity和生命周期…

谁说QTP不能多线程 - 当Python遇上QTP

谁说QTP不能多线程 - 当Python遇上QTP 作者&#xff1a;Wally Yu (微博&#xff1a;http://weibo.com/quicktest) 经常有人问我一个问题&#xff1a;QTP可以同时做多个项目的自动化吗&#xff1f;我每次都回答说“不行&#xff0c;QTP不支持多线程&#xff0c;VBS本身就不是…

验证手机号码工具类

/*** 验证手机号码&#xff08;支持国际格式&#xff0c;86135xxxx...&#xff08;中国内地&#xff09;&#xff0c;00852137xxxx...&#xff08;中国香港&#xff09;&#xff09;* param mobile 移动、联通、电信运营商的号码段*<p>移动的号段&#xff1a;134(0-8)、1…

Android中使用隐藏API图文解析

Android SDK的很多API是隐藏的&#xff0c;我无法直接使用。但是我们通过编译Android系统源码可以得到完整的API。编译Android系统源码后可以在out\target\common\obj\JAVA_LIBRARIES目录可以看到它的所有API。当然对于一般情况&#xff0c;out\target\common\obj\JAVA_LIBRARI…

QTP测试框架之_报表

QTP测试框架之_报表 作者&#xff1a;Wally Yu (微博&#xff1a;http://weibo.com/quicktest) 自己在开发QTP测试框架的时候一些对于报表的经验&#xff1a; Excel报表&#xff1a; 下载Report Manager:http://www.advancedqtp.com/knowl ... ut-reportermanager/ 修改…

git克隆github_如何使用Git和Github分叉,克隆和推送更改

git克隆github介绍 (Introduction) Github is an excellent resource for finding useful code. In order to contribute changes back to a project, you’ll need to make a local copy and then upload your changes. In this tutorial, you’ll fork and clone an existing…

LBS模块架构的封装

对地图进行一个封装 public interface ILbsLayer {/*** 获取地图*/View getMapView();/*** 设置位置变化监听*/void setLocationChangeListener(CommonLocationChangeListener locationChangeListener);/*** 设置定位图标*/void setLocationRes(int res);/*** 添加&#xf…

[收藏]张翼轸:在Outlook的名义下

张翼轸&#xff1a;在Outlook的名义下 -------------------------------------------------------------------------------- http://www.sina.com.cn 2005年03月08日 14:48 ChinaByte   文/张翼轸Plaxo、Teleo、Skype这几个不同的SNS(Social Network Software&#xff0c;…