TypeScript In React实践指南

TypeScript in React

前言

  • 适用范围

    本文不适合当作 TS 的入门资料,因为本文不会介绍基础的TS语法,而是从项目实践角度出发,讲解TS与React怎样更好的结合使用。

  • 动机

    项目中虽然使用了 TS,也切身体会到了静态类型检查带给项目在可维护性上的优势,但是在实际的项目开发中也遇到了由它带来的种种束缚,对 TS 始终又爱又恨。其次,接触 TS 有半年多的时间了,对自己来说,也是总结与回顾的一个好时机。

  • 问题:

    • 项目开发中浪费在编写 TS 类型注解、消灭各种红波浪报错的时间甚至超过了正式功能的代码编写时间。(一个理想的时间分配大概是,类型注解 20%,功能逻辑 80%)
    • 开发完成后 review 代码,看着代码中处处都是的 any 类型,完全不知从哪着手优化。
    • 系统学习了 TS,在纯 JS 项目中得心应手,但是一到 react 中就各种水土不服。
  • 原因

    • 官方文档,缺乏一些最佳实践的引导。网上的学习资料、讨论也不如其他的前端技术栈来的丰富。
    • react官方并没有阐述 react 与 TS 结合使用的详细指导文档
  • 目的

    尝试解决上述问题,提升读者 TS 实战能力

TS 编写 react 组件

一、从声明一个组件开始

  • 函数式组件声明方式
    1. 方式一(推荐): 将组件用React.FC< P > 这个官方的函数组件泛型接口来声明。

    优势(1)props 自带 children 声明 (2)defaultProps、propsTypes、displayName 等的所有react组件静态属性能够获得 IDE 的友好提示。

      interface Props {
        text:string
        theme:Theme
      }
      const Button:React.FC<Props> = (props) => {
          const { text } = props;
          return <div><button>{text}</button></div>;
      };
    复制代码
    1. 方式二 : 自行处理 children 声明
    interface Props {
        text:string
        theme:Theme
        children?: ReactNode
      }
      const Button = (props:Props) => {
          const { text, children } = props;
          return <div><button>{text}</button>{children}</div>;
      };
    复制代码
    1. 方式三 : 利用 PropsWithChildren< P > 处理 children。效果同方式二一样。
     interface Props {
        text:string
        theme:Theme
      }
      const Button = (props: React.PropsWithChildren<Props>) => {
          const { text, children } = props;
          return <div><button>{text}</button>{children}</div>;
      };
    复制代码
    React.FC(推荐) 自行处理children属性 PropsWithChildren
    自动children声明
    react静态方法声明
  • class 组件声明方式
    一般用Component 官方提供的泛型类来定义

      interface Props{
        id: string
      }
      interface State{
          count: number
      }
      class Button extends Component<Props, State> {
          state = {
              count: 0,
          }
          add = () => {
              this.setState({
                  count: this.state.count + 1,
              });
          }
          render() {
              return <div>{this.state.count}<button onClick={this.add}>add</button></div>;
          }
    }
    复制代码

二、Props 校验及默认值

  • Props 校验

TS 类型约束 vs propsType等第三方库
“`
// 使用TS interface约束props (推荐)
interface Props {
text:string
theme:Theme
}
const Button:React.FC = (props) => {
const { text } = props;
return

{text}

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享