当前位置: 首页 > article >正文

react ts 定义基本类型,组件通过ref调用时类型提示

记录,以防忘记

子组件

import React, { forwardRef, Ref, useImperativeHandle, useState } from 'react';

// 类型定义方式1
interface IProps {
     /**参数1 */
    params1: number | string | undefined
    /**参数2 */
    params2: number | string | undefined
    /**方法 */
    openDialog: () => void
}


// 类型定义方式2
type PaginationType = {
    /**当前页 */
    page: number,
    /**每页条数 */
    pageSize: number
    /**总数 */
    total: number
}

// 这里定义ref的类型,外面调用时会有提示
export interface AppRef {
    /**方法说明 */
    report: () => void
}

const App = ({ params1, params2, openDialog }: IProps, ref: Ref<AppRef>) => {

    const [pagination, setPagination] = useState<PaginationType>({ page: 1, pageSize: 10, total: 0 })

    const init = () => {
        console.log('------------这里执行触发');
    }

    useImperativeHandle(ref, () => ({
        report: () => init()
    }))

    return <>
        {/* 选择时会有提示 */}
        {pagination.page}
    </>
}

export default forwardRef(App);

父组件

// 使用时
import React, { useRef } from 'react';
import App, { AppRef } from './app.tsx';
const AppContent = () => {
    // 默认子组件的ref给null
    const AppRef = useRef<AppRef>(null)

    // 这样调用子组件的方法时,会有提示
    AppRef.current?.report()

    return <App ref={AppRef} />
}
export default AppContent;

动态属性对象: 使用索引签名([key: string]: type)来表示对象的动态属性

interface Dictionary {
  [key: string]: string;
}

let dict: Dictionary = { a: "apple", b: "banana" };

交叉类型(Intersection Types)

interface Person {
  name: string;
}

interface Worker {
  job: string;
}

type Employee = Person & Worker;

let employee: Employee = { name: "John", job: "Engineer" };

数组类型

type ItemType = {
    id: number,
    name: string
}


const list:Array<ItemType>=[{id: 1, name: '张三'},{id: '2', name: '李四'}]

const list1:Array<string|number>=[1, '2', 3]

Partial: 将一个类型的所有属性都变为可选

interface Person {
  name: string;
  age: number;
}

type PartialPerson = Partial<Person>;  // 所有属性都变为可选
let partialPerson: PartialPerson = { name: "John" };

Required: 将一个类型的所有属性都变为必需

type RequiredPerson = Required<Person>;  // 所有属性变为必需
let fullPerson: RequiredPerson = { name: "John", age: 30 };  // 必须包含 name 和 age

Pick: 从类型中选择一部分属性

type NameOnly = Pick<Person, "name">;
let nameOnly: NameOnly = { name: "John" };


http://www.kler.cn/a/488217.html

相关文章:

  • 如何解决 VS Code 调试时无法查看 std 中变量的问题
  • pgsql 连接数查看、释放
  • 【AniGS】论文阅读
  • Docker 通过创建Dockerfile 部署Jar包
  • MATLAB对文件处理
  • springboot整合gateway
  • 多云架构,JuiceFS 如何实现一致性与低延迟的数据分发
  • [IoT]解决方案设计:智能农业监控系统
  • pytorch模型的保存失敗しましたが、
  • JVM生产环境常用参数配置及调优建议
  • vue3+ElementPlus+VueCropper实现上传图片
  • Day97 minio
  • 详细分析 创建并上传到 GitHub 仓库
  • 【每日学点鸿蒙知识】调试、网络、缓存、富文本编辑等
  • Unity学习之UGUI进阶
  • android studio使用DataBinding
  • Unity使用Vuforia插件进行AR开发
  • Django REST framework 源码剖析-视图集详解(ViewSet)
  • 使用Logstash 将Mysql的数据导入ElasticSearch中
  • (超详细)Maven安装配置、以及在IDEA中创建Maven项目