环境搭建

我们当然可以先用脚手架搭建React项目,然后手动配置成支持TypeScript的环境,虽然比较麻烦,但可以让你更清楚整个过程。这里比较麻烦,就不演示了,直接用命令配置好。

  1. npx create-react-app appname --typescript

可以安装一些自己需要的库及其声明文件,例如react-router-dom、axios、ant Design等。如果要安装ant design,还需要在开发环境库中安装一些依赖库,以帮助实现按需加载。

使用

有类型约束的函数组件

  1. import React from "react";
  2. import { Button } from "antd";
  3.  
  4. interface Greeting {
  5. name: string;
  6. firstName?: string;
  7. lastName?: string;
  8. }
  9.  
  10. // 没有使用React.FC
  11. const HelloOld = (props: Greeting) => <Button>你好{props.name}</Button>;
  12.  
  13. // 使用React.FC泛型类型
  14. const Hello: React.FC<Greeting> = (props) => {
  15. return (
  16. <Button>Hello {props.name}</Button>
  17. )
  18. };
  19.  
  20. export { Hello, HelloOld };

定义函数组件时,使用React.FC与不使用没有太多区别,没有为我们带来明显的好处,建议使用常规定义方式。

有类型约束的类组件

  1. import React,{Fragment} from "react";
  2. import { Button } from "antd";
  3.  
  4. interface Greeting {
  5. name: string;
  6. firstName?: string;
  7. lastName?: string;
  8. }
  9. interface State {
  10. count: number
  11. }
  12.  
  13. // 泛型类型,第一个传入参数约束属性props,第二个约束状态state(内部数据)
  14. class HelloClass extends React.Component<Greeting, State> {
  15. state: State = {
  16. count: 0
  17. };
  18. static defaultProps = { // 属性默认值
  19. firstName: "",
  20. lastName: "",
  21. };
  22.  
  23. render() {
  24. return (
  25. <Fragment>
  26. <p>点击了{this.state.count}次</p>
  27. <Button onClick={()=>{this.setState({count: this.state.count+1})}}>Hello{this.props.name}Class</Button>
  28. </Fragment>
  29. );
  30. }
  31. }
  32.  
  33. export default HelloClass;

有类型约束的高阶组件

  1. import React from "react";
  2. import HelloClass from "./HelloClass";
  3.  
  4. interface Loading {
  5. loading: boolean;
  6. }
  7.  
  8. function HelloHoc<P>(params?: any) {
  9. return function<P>(WrappedComponent: React.ComponentType<P>) { // P表示被包装组件的属性的类型
  10. return class NewComponent extends React.Component<P & Loading>{ // 这里使用交叉类型,为新组件增加一些属性,接口Loading定义了新增的属性声明
  11. render(){
  12. return this.props.loading ? <div>Loading</div> : <WrappedComponent {...this.props as P}/>
  13.  
  14. }
  15. }
  16. }
  17. }
  18.  
  19. export default HelloHoc()(HelloClass);

高阶组件在ts中使用会有比较多的类型问题,解决这些问题通常不会很顺利,而且会存在一些已知的bug,这不是高阶组件本身的问题,而是React声明文件还没有很好地兼容高阶组件的类型检查,更好的方式是使用Hooks

有类型约束的Hooks

  1. import React, { useState, useEffect } from "react";
  2. import { Button } from "antd";
  3.  
  4. interface Greeting {
  5. name: string;
  6. firstName?: string;
  7. lastName?: string;
  8. }
  9.  
  10. const HelloHooks = (props: Greeting) => {
  11. const [ count, setCount ] = useState(0); // 设了初值,所以不用定义类型
  12. const [ text, setText ] = useState<string | null>(null);
  13.  
  14. useEffect(()=>{
  15. count > 5 && setText("休息一下");
  16. },[count]); // 第二个参数的作用是,只有当count改变的时候,函数内的逻辑才会执行。
  17.  
  18. return (
  19. <>
  20. <p>你点击了Hooks {count} {text}</p>
  21. <Button onClick={()=>{setCount(count+1)}}>{props.name}</Button>
  22. </>
  23. );
  24. };
  25.  
  26. export default HelloHooks;

事件绑定

  1. class HelloClass extends React.Component<Greeting, State> {
  2. state: State = {
  3. count: 0
  4. };
  5.  
  6. clickHandle = (e: React.MouseEvent) => { // 事件对象e的类型使用内置的合成事件。在回调函数中,e的属性都会无效
  7. e.persist(); // 将该事件从池中删除合成事件,可以正常使用
  8. console.log(e);
  9. // this.setState({count: this.state.count+1})
  10. };
  11.  
  12. inputHandle = (e: React.FormEvent<HTMLInputElement>) => {
  13. // e.persist();
  14. console.log(e.currentTarget.value); // 此时编译器报错,认为没有value属性,需要指定<HTMLInputElement>泛型类型
  15. // console.log(e.target.value); // 仍然不行
  16. };
  17.  
  18. render() {
  19. return (
  20. <Fragment>
  21. <p>点击了{this.state.count}次</p>
  22. <Button onClick={this.clickHandle}>Hello{this.props.name}Class</Button>
  23. <input onChange={this.inputHandle}/>
  24. </Fragment>
  25. );
  26. }
  27. }

TypeScript && React的更多相关文章

  1. Nodejs生态圈的TypeScript+React

    基于Nodejs生态圈的TypeScript+React开发入门教程   基于Nodejs生态圈的TypeScript+React开发入门教程 概述 本教程旨在为基于Nodejs npm生态圈的前端程 ...

  2. 基于Nodejs生态圈的TypeScript+React开发入门教程

    基于Nodejs生态圈的TypeScript+React开发入门教程   概述 本教程旨在为基于Nodejs npm生态圈的前端程序开发提供入门讲解. Nodejs是什么 Nodejs是一个高性能Ja ...

  3. typescript+react+antd基础环境搭建

    typescript+react+antd基础环境搭建(包含样式定制) tsconfig.json 配置 // 具体配置可以看上面的链接 这里module moduleResolution的配置都会影 ...

  4. TypeScript & React & Jest

    TypeScript & React & Jest create-react-app Jest ``tsx import React from 'react'; import { re ...

  5. Typescript & React & Vue

    Typescript & React & Vue Typescript & React https://facebook.github.io/create-react-app/ ...

  6. Typescript & React & optional parameters & default parameters

    Typescript & React & optional parameters & default parameters Typescript & optional ...

  7. 从零开始配置TypeScript + React + React-Router + Redux + Webpack开发环境

    转载请注明出处! 说在前面的话: 1.为什么不使用现成的脚手架?脚手架配置的东西太多太重了,一股脑全塞给你,我只想先用一些我能懂的库和插件,然后慢慢的添加其他的.而且自己从零开始配置也能学到更多的东西 ...

  8. webpack构建多页面react项目(webpack+typescript+react)

    目录介绍 src:里面的每个文件夹就是一个页面,页面开发相关的组件.图片和样式文件就存放在对应的文件夹下. tpl:里面放置模板文件,当webpack打包时为html-webpack-plugin插件 ...

  9. TypeScript + React + Redux 实战简单天气APP全套完整项目

    下载链接:https://www.yinxiangit.com/171.html 目录: 从面向过程的js到面向对象的js,让web前端更加高大尚.让你的前端步步日上,紧跟技术发展的前沿.让你构建更加 ...

随机推荐

  1. IntelliJ IDEA + Maven + Jetty + Jersey搭建RESTful服务

    这次参考的是这个博客,完全按照这个我这里会出一些问题,一会再说就是了. https://www.cnblogs.com/puyangsky/p/5368132.html 一.首先新建一个项目,选择Ja ...

  2. JWT+Interceptor实现无状态登录和鉴权

    无状态登录原理 先提一下啥是有状态登录 单台tomcat的情况下:编码的流程如下 前端提交表单里用户的输入的账号密码 后台接受,查数据库, 在数据库中找到用户的信息后,把用户的信息存放到session ...

  3. vue+element搭建后台管理界面(支持table条件搜索)

    代码地址(如果有帮助,请点个Star) vue:https://github.com/wwt729/ElementUIAdmin-master.git springboot后端:https://git ...

  4. webgl(three.js)实现室内定位,楼宇bim、实时定位三维可视化解决方案

    (写在前面,谈谈物联网展会)上次深圳会展中心举行物联网展会,到了展会一看,80%以上的物联网应用都是在搞RFID,室内定位,我一度怀疑物联网落地方案的方向局限性与市场导向,后来多方面了解才明白,展会上 ...

  5. python(自用手册)三

    第三章 基础 3.1编码初识 ascii 256字母没有中文 一个字节 8位 gbk 中国 中文2字节 16位 英文1字节8位 unicode 万国码 前期 2字节 8位 后期变成4个字节 32位 u ...

  6. CentOS -- Zookeeper installation and configure

    1 JDK 1.8 must installed first 2 Get Zookeeper package wget https://archive.apache.org/dist/zookeepe ...

  7. JNI开发流程

    交叉编译 在一个平台上去编译另一个平台上可以执行的本地代码 cpu平台 arm x86 mips 操作系统平台 windows linux mac os 原理 模拟不同平台的特性去编译代码 jni开发 ...

  8. Chrome 开发工具之 Application

    Chrome 开发者工具有 Application 这么一个面板,主要作用是检查 web 应用加载的所有资源,包括 Manifest.Service Workers.Local Storage.Ses ...

  9. UML类图详解和示例

    ps:博客园markdown不能自动生成列表,更好的阅读体验可访问我的个人博客http://www.isspark.com/archives/UMLDescription UML类图概述 什么是UML ...

  10. 前端利器躬行记(3)——webpack基础

    webpack是一个静态模块打包器,此处的模块可以是任意文件,包括Sass.TypeScript.模板和图像等.webpack可根据输入文件的依赖关系,打包输出浏览器可识别的JavaScript.CS ...