react常见的ts类型实践解析

 更新时间:2023年04月16日 10:30:33   作者:Maic  
这篇文章主要为大家介绍了react常见的ts类型实践解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

正文

ts在中在react用处很是很广泛,本文是一篇关于在react中常用的类型总结,希望能带来一些思考和帮助。

  • 一个函数组件
import React from "react";
type Props = {
}
const Header: React.FC<Props> = (props) => {
  return (<>
    <div>header</div>
    {props.children}
  </>)
}

我们注意在Header组件中有使用到props.children如果Props没有申明类型那么此时就会报这样的错误

此时我们需要加个类型就行,并且children是可选的

import React from "react";
interface Props {
  children?: React.ReactNode;
}

除了children,有时我想给Header组件传入一个className,并且是可选的

import React from "react";
type Props = {
 children?: React.ReactNode;
 className?: string;
}
const Header: React.FC<Props> = (props) => {
  const { className } = props;
  return (<>
    <div className={`App-header ${className}`}>header</div>
    {props.children}
  </>)
}

Props我们似乎对每一个可选项都有做?可选,有没有一劳永逸的办法

Partial<T>所有属性都是可选

import React from "react";
type Props = {
 children: React.ReactNode;
 className: string;
}
const Header: React.FC<Partial<Props>> = (props) => {
  const { className = '' } = props;
  return (<>
    <div className={`App-header ${className}`}>header</div>
    {props.children}
  </>)
}

在以上我们给Props申明了一个children?: React.ReactNode,如果你不想这么写,react也提供了一个属性PropsWithChildren

interface ChildProps {}
export const SubHeader: React.FC = (
  props: PropsWithChildren<{}> & Partial<ChildProps>
) => {
  return <div className={`sub-header`}>{props.children}</div>;
};

在dom节点上的类型

import React, { PropsWithChildren, useRef } from "react";
const Input: React.FC = () => {
  const inputRef = useRef<HTMLInputElement>(null);
  const sureRef = useRef<HTMLDivElement>(null);
  return (
    <>
      <input type="text" ref={inputRef} />
      <div ref={sureRef}>确定</div>
    </>
  );
};

传入子组件的方法

我想传入一个方法到子组件里去

type InputProps = {
  onSure: () => void;
};
const Input: React.FC<InputProps> = (props) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const sureRef = useRef<HTMLDivElement>(null);
  return (
    <>
      <input type="text" ref={inputRef} />
      <div ref={sureRef} onClick={props?.onSure}>
        确定
      </div>
    </>
  );
};
const Index: React.FC<Partial<Props>> = (props) => {
  const { className } = props;
  const handleSure = () => {};
  return (
    <header className={`App-header ${className}`}>
      <Input onSure={handleSure} />
      {props.children}
    </header>
  );
};

!非空断言,一定有该方法或者属性

  const body = document!.getElementsByTagName("body")[0];
  body.addEventListener("click", () => {
    console.log("body");
  });

一个doms上的类型

sure按钮上用ref绑定一个dom

const Input: React.FC<InputProps> = (props) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const sureRef = useRef(null);
  const body = document!.getElementsByTagName("body")[0];
  body.addEventListener("click", () => {
    console.log(sureRef.current?.style);
    console.log("body");
  });
  return (
    <>
      <input type="text" ref={inputRef} />
      <div ref={sureRef} onClick={props?.onSure}>
        确定
      </div>
    </>
  );
};

此时我们需要给sureRef申明类型,并且?访问可选属性

const inputRef = useRef<HTMLInputElement>(null);
const sureRef = useRef<HTMLDivElement>(null);
const body = document!.getElementsByTagName("body")[0];
body.addEventListener("click", () => {
  console.log(sureRef.current?.style);
  console.log("body");
});

导入一个组件需要的多个类型

// userInterfence.ts
export type UserInfo = {
  name: string;
  age: number;
};
export type Menu = {
  title: string;
  price: number;
  isChecked: boolean;
  items: Array<{
    name: string;
    price: number;
  }>;
};

在另外一个组件引入

import type { UserInfo, Menu } from "./userInterfence";
const Input: React.FC<InputProps> = (props) => {
  const [userInfo, setUserInfo] = useState<UserInfo>({
    name: "Web技术学苑",
    age: 10,
  });
  const inputRef = useRef<HTMLInputElement>(null);
  const sureRef = useRef<HTMLDivElement>(null);
  const body = document!.getElementsByTagName("body")[0];
  body.addEventListener("click", () => {
    console.log(sureRef.current?.style);
    console.log("body");
  });
  return (
    <>
      <input type="text" ref={inputRef} value={userInfo.name} />
      <input type="text" value={userInfo.age} />
      <div ref={sureRef} onClick={props?.onSure}>
        确定
      </div>
    </>
  );
};

选择一个组件的指定的几个属性

在两个类似的组件,我们有一些公用的属性,此时我们的类型可以借用Omit去掉一些不需要的属性类型

import type { UserInfo, Menu } from "./userInterfence";
const MenuComp: React.FC<Omit<Menu, "items" | "isChecked">> = (props) => {
  return (
    <>
      <p>{props.price}</p>
      <p>{props.title}</p>
    </>
  );
};

header组件中引入

<header className={`App-header ${className}`}>
    <MenuComp price={10} title={"menuA"} />
    {props.children}
  </header>

或者你可以使用Pick来选择指定的属性

import type { UserInfo, Menu } from "./userInterfence";
const MenuSubComp: React.FC<Pick<Menu, "items">> = (props) => {
  return (
    <>
      <p>{props.items[0].name}</p>
      <p>{props.items[0].price}</p>
    </>
  );
};

另一个组件中使用

const Index: React.FC<Partial<Props>> = (props) => {
  const { className } = props;
  const subInfo: Pick<Menu, "items"> = {
    items: [
      {
        name: "Web技术学苑",
        price: 10,
      },
    ],
  };
  return (
    <header className={`App-header ${className}`}>
      <MenuComp price={10} title={"menuA"} />
      <MenuSubComp items={subInfo.items} />
      {props.children}
    </header>
  );
};

总结

react高频常用的ts,比如如何申明一个组件的返回的类型,以及接收props的参数

如何申明一个dom上的类型,以及如何传入一个函数到子组件的类型

!?的使用,当我们知道一定有该属性时,你可以使用!,如果一个属性是可选的那么就用?

OmitPick在组件中的使用,更多typescript参考官方文档学习

本文code example

以上就是react常见的ts类型实践解析的详细内容,更多关于react常见的ts类型的资料请关注脚本之家其它相关文章!

相关文章

  • react-native 配置@符号绝对路径配置和绝对路径没有提示的问题

    react-native 配置@符号绝对路径配置和绝对路径没有提示的问题

    本文主要介绍了react-native 配置@符号绝对路径配置和绝对路径没有提示的问题,文中通过图文示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-01-01
  • react配置webpack-bundle-analyzer项目优化踩坑记录

    react配置webpack-bundle-analyzer项目优化踩坑记录

    这篇文章主要介绍了react配置webpack-bundle-analyzer项目优化踩坑记录,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • React 实现拖拽功能的示例代码

    React 实现拖拽功能的示例代码

    这篇文章主要介绍了React 实现拖拽功能的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01
  • React实践之Tree组件的使用方法

    React实践之Tree组件的使用方法

    本篇文章主要介绍了React实践之Tree组件的使用方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • 浅谈React Component生命周期函数

    浅谈React Component生命周期函数

    React组件有哪些生命周期函数?类组件才有的生命周期函数,分为几个阶段:挂载,更新,卸载,错误处理,本文主要介绍了这个阶段,感兴趣的可以了解一下
    2021-06-06
  • 详解如何在React中监听鼠标事件

    详解如何在React中监听鼠标事件

    React可以通过使用React事件系统来监听鼠标事件,您可以在React组件中通过使用特定的事件处理函数来注册和处理鼠标事件,本文小编讲给大家详细介绍一下如何在React中监听鼠标事件,需要的朋友可以参考下
    2023-09-09
  • react-router-dom的使用说明

    react-router-dom的使用说明

    这篇文章主要介绍了react-router-dom的使用说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-03-03
  • React Form组件的实现封装杂谈

    React Form组件的实现封装杂谈

    这篇文章主要介绍了React Form组件的实现封装杂谈,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • React框架核心原理全面深入解析

    React框架核心原理全面深入解析

    React是前端开发每天都用的前端框架,自然要深入掌握它的原理。我用 React 也挺久了,这篇文章就来总结一下我对 react 原理的理解,有需要的朋友可以借鉴参考下,希望能够有所帮助
    2022-11-11
  • react.js 翻页插件实例代码

    react.js 翻页插件实例代码

    这篇文章主要介绍了react.js 翻页插件实例代码的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2017-01-01

最新评论