记录,以防忘记
子组件
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给nullconst 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" };