TypeScript && React
环境搭建
我们当然可以先用脚手架搭建React项目,然后手动配置成支持TypeScript的环境,虽然比较麻烦,但可以让你更清楚整个过程。这里比较麻烦,就不演示了,直接用命令配置好。
- npx create-react-app appname --typescript
可以安装一些自己需要的库及其声明文件,例如react-router-dom、axios、ant Design等。如果要安装ant design,还需要在开发环境库中安装一些依赖库,以帮助实现按需加载。
使用
有类型约束的函数组件
- import React from "react";
- import { Button } from "antd";
- interface Greeting {
- name: string;
- firstName?: string;
- lastName?: string;
- }
- // 没有使用React.FC
- const HelloOld = (props: Greeting) => <Button>你好{props.name}</Button>;
- // 使用React.FC泛型类型
- const Hello: React.FC<Greeting> = (props) => {
- return (
- <Button>Hello {props.name}</Button>
- )
- };
- export { Hello, HelloOld };
定义函数组件时,使用React.FC与不使用没有太多区别,没有为我们带来明显的好处,建议使用常规定义方式。
有类型约束的类组件
- import React,{Fragment} from "react";
- import { Button } from "antd";
- interface Greeting {
- name: string;
- firstName?: string;
- lastName?: string;
- }
- interface State {
- count: number
- }
- // 泛型类型,第一个传入参数约束属性props,第二个约束状态state(内部数据)
- class HelloClass extends React.Component<Greeting, State> {
- state: State = {
- count: 0
- };
- static defaultProps = { // 属性默认值
- firstName: "",
- lastName: "",
- };
- render() {
- return (
- <Fragment>
- <p>点击了{this.state.count}次</p>
- <Button onClick={()=>{this.setState({count: this.state.count+1})}}>Hello{this.props.name}Class</Button>
- </Fragment>
- );
- }
- }
- export default HelloClass;
有类型约束的高阶组件
- import React from "react";
- import HelloClass from "./HelloClass";
- interface Loading {
- loading: boolean;
- }
- function HelloHoc<P>(params?: any) {
- return function<P>(WrappedComponent: React.ComponentType<P>) { // P表示被包装组件的属性的类型
- return class NewComponent extends React.Component<P & Loading>{ // 这里使用交叉类型,为新组件增加一些属性,接口Loading定义了新增的属性声明
- render(){
- return this.props.loading ? <div>Loading</div> : <WrappedComponent {...this.props as P}/>
- }
- }
- }
- }
- export default HelloHoc()(HelloClass);
高阶组件在ts中使用会有比较多的类型问题,解决这些问题通常不会很顺利,而且会存在一些已知的bug,这不是高阶组件本身的问题,而是React声明文件还没有很好地兼容高阶组件的类型检查,更好的方式是使用Hooks
有类型约束的Hooks
- import React, { useState, useEffect } from "react";
- import { Button } from "antd";
- interface Greeting {
- name: string;
- firstName?: string;
- lastName?: string;
- }
- const HelloHooks = (props: Greeting) => {
- const [ count, setCount ] = useState(0); // 设了初值,所以不用定义类型
- const [ text, setText ] = useState<string | null>(null);
- useEffect(()=>{
- count > 5 && setText("休息一下");
- },[count]); // 第二个参数的作用是,只有当count改变的时候,函数内的逻辑才会执行。
- return (
- <>
- <p>你点击了Hooks {count} 次 {text}</p>
- <Button onClick={()=>{setCount(count+1)}}>{props.name}</Button>
- </>
- );
- };
- export default HelloHooks;
事件绑定
- class HelloClass extends React.Component<Greeting, State> {
- state: State = {
- count: 0
- };
- clickHandle = (e: React.MouseEvent) => { // 事件对象e的类型使用内置的合成事件。在回调函数中,e的属性都会无效
- e.persist(); // 将该事件从池中删除合成事件,可以正常使用
- console.log(e);
- // this.setState({count: this.state.count+1})
- };
- inputHandle = (e: React.FormEvent<HTMLInputElement>) => {
- // e.persist();
- console.log(e.currentTarget.value); // 此时编译器报错,认为没有value属性,需要指定<HTMLInputElement>泛型类型
- // console.log(e.target.value); // 仍然不行
- };
- render() {
- return (
- <Fragment>
- <p>点击了{this.state.count}次</p>
- <Button onClick={this.clickHandle}>Hello{this.props.name}Class</Button>
- <input onChange={this.inputHandle}/>
- </Fragment>
- );
- }
- }
TypeScript && React的更多相关文章
- Nodejs生态圈的TypeScript+React
基于Nodejs生态圈的TypeScript+React开发入门教程 基于Nodejs生态圈的TypeScript+React开发入门教程 概述 本教程旨在为基于Nodejs npm生态圈的前端程 ...
- 基于Nodejs生态圈的TypeScript+React开发入门教程
基于Nodejs生态圈的TypeScript+React开发入门教程 概述 本教程旨在为基于Nodejs npm生态圈的前端程序开发提供入门讲解. Nodejs是什么 Nodejs是一个高性能Ja ...
- typescript+react+antd基础环境搭建
typescript+react+antd基础环境搭建(包含样式定制) tsconfig.json 配置 // 具体配置可以看上面的链接 这里module moduleResolution的配置都会影 ...
- TypeScript & React & Jest
TypeScript & React & Jest create-react-app Jest ``tsx import React from 'react'; import { re ...
- Typescript & React & Vue
Typescript & React & Vue Typescript & React https://facebook.github.io/create-react-app/ ...
- Typescript & React & optional parameters & default parameters
Typescript & React & optional parameters & default parameters Typescript & optional ...
- 从零开始配置TypeScript + React + React-Router + Redux + Webpack开发环境
转载请注明出处! 说在前面的话: 1.为什么不使用现成的脚手架?脚手架配置的东西太多太重了,一股脑全塞给你,我只想先用一些我能懂的库和插件,然后慢慢的添加其他的.而且自己从零开始配置也能学到更多的东西 ...
- webpack构建多页面react项目(webpack+typescript+react)
目录介绍 src:里面的每个文件夹就是一个页面,页面开发相关的组件.图片和样式文件就存放在对应的文件夹下. tpl:里面放置模板文件,当webpack打包时为html-webpack-plugin插件 ...
- TypeScript + React + Redux 实战简单天气APP全套完整项目
下载链接:https://www.yinxiangit.com/171.html 目录: 从面向过程的js到面向对象的js,让web前端更加高大尚.让你的前端步步日上,紧跟技术发展的前沿.让你构建更加 ...
随机推荐
- IntelliJ IDEA + Maven + Jetty + Jersey搭建RESTful服务
这次参考的是这个博客,完全按照这个我这里会出一些问题,一会再说就是了. https://www.cnblogs.com/puyangsky/p/5368132.html 一.首先新建一个项目,选择Ja ...
- JWT+Interceptor实现无状态登录和鉴权
无状态登录原理 先提一下啥是有状态登录 单台tomcat的情况下:编码的流程如下 前端提交表单里用户的输入的账号密码 后台接受,查数据库, 在数据库中找到用户的信息后,把用户的信息存放到session ...
- vue+element搭建后台管理界面(支持table条件搜索)
代码地址(如果有帮助,请点个Star) vue:https://github.com/wwt729/ElementUIAdmin-master.git springboot后端:https://git ...
- webgl(three.js)实现室内定位,楼宇bim、实时定位三维可视化解决方案
(写在前面,谈谈物联网展会)上次深圳会展中心举行物联网展会,到了展会一看,80%以上的物联网应用都是在搞RFID,室内定位,我一度怀疑物联网落地方案的方向局限性与市场导向,后来多方面了解才明白,展会上 ...
- python(自用手册)三
第三章 基础 3.1编码初识 ascii 256字母没有中文 一个字节 8位 gbk 中国 中文2字节 16位 英文1字节8位 unicode 万国码 前期 2字节 8位 后期变成4个字节 32位 u ...
- CentOS -- Zookeeper installation and configure
1 JDK 1.8 must installed first 2 Get Zookeeper package wget https://archive.apache.org/dist/zookeepe ...
- JNI开发流程
交叉编译 在一个平台上去编译另一个平台上可以执行的本地代码 cpu平台 arm x86 mips 操作系统平台 windows linux mac os 原理 模拟不同平台的特性去编译代码 jni开发 ...
- Chrome 开发工具之 Application
Chrome 开发者工具有 Application 这么一个面板,主要作用是检查 web 应用加载的所有资源,包括 Manifest.Service Workers.Local Storage.Ses ...
- UML类图详解和示例
ps:博客园markdown不能自动生成列表,更好的阅读体验可访问我的个人博客http://www.isspark.com/archives/UMLDescription UML类图概述 什么是UML ...
- 前端利器躬行记(3)——webpack基础
webpack是一个静态模块打包器,此处的模块可以是任意文件,包括Sass.TypeScript.模板和图像等.webpack可根据输入文件的依赖关系,打包输出浏览器可识别的JavaScript.CS ...