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在组件中的使用,更多typescriptopen in new window参考官方文档学习

  • 本文code exampleopen in new window

扫二维码,关注公众号
专注前端技术,分享web技术
加作者微信
扫二维码 备注 【加群】
教你聊天恋爱,助力脱单
微信扫小程序二维码,助你寻他/她
专注前端技术,分享Web技术
微信扫小程序二维码,一起学习,一起进步
前端面试大全
海量前端面试经典题,助力前端面试