温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

react常见的ts类型怎么定义

发布时间:2023-04-17 17:19:40 来源:亿速云 阅读:124 作者:iii 栏目:开发技术

本篇内容主要讲解“react常见的ts类型怎么定义”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“react常见的ts类型怎么定义”吧!

  • 一个函数组件

import React from "react";
type Props = {
}
const Header: React.FC<Props> = (props) => {
  return (<>
    <div>header</div>
    {props.children}
  </>)
}

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

react常见的ts类型怎么定义

此时我们需要加个类型就行,并且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>
    </>
  );
};

react常见的ts类型怎么定义

此时我们需要给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>
    </>
  );
};

react常见的ts类型怎么定义

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

在两个类似的组件,我们有一些公用的属性,此时我们的类型可以借用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类型怎么定义”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI