马格南摄影网站,网站每年都要续费吗,网站新建设请示,网站响应度在学习 React 时#xff0c;我们总会遇到在 TS 和 JS 之间切换来开发多个项目#xff0c;而有时会忘记 TS 的语法#xff0c;所以编写一下 React 结合 TS 开发时的一些总结知识点#xff0c;以便后续回顾用。
向组件传递基础参数#xff08;字符串、数字和布尔值#xf…在学习 React 时我们总会遇到在 TS 和 JS 之间切换来开发多个项目而有时会忘记 TS 的语法所以编写一下 React 结合 TS 开发时的一些总结知识点以便后续回顾用。
向组件传递基础参数字符串、数字和布尔值
这节主要是介绍一下在 React TS 中如何实现组件传递基础类型的参数。具体实例如下
type BasePropData {name: string;age: number;isGraduate: boolean;
};const BaseProps: React.FCBasePropData ({ name, age, isGraduate }) {return (divh2传递基础参数实例/h2pname: {name}/ppage: {age}/ppisGraduate {isGraduate ? 是 : 否}/p/div);
};export default BaseProps;向组件传递对象参数数组、对象和多值情况
这节主要是介绍一下在 React TS 中如何实现组件传递数组、对象和联合类型的的参数。具体实例如下
type StudentProps {id: number;name: string;age: number;
};type ObjectPropsData {students: StudentProps[];classInfo: {no: string;name: string;roomNo: string;studentCount: number;grade: 初一 | 初二 | 初三;};
};const ObjectProps: React.FCObjectPropsData (props) {return (divh2传递对象参数实例/h2divh4班级信息/h4hr /p年级编号{props.classInfo.no}/pp年级名称{props.classInfo.name}/pp教室编号{props.classInfo.roomNo}/pp学生数量{props.classInfo.studentCount}/pp班级年级{props.classInfo.grade}/p/divdivh4学生姓名/h4hr /{props.students.map((item) (p姓名{item.name} 年龄{item.age}/p))}/div/div);
};export default ObjectProps;向组件传递 children 参数
这节主要是介绍一下在 React TS 中如何实现组件传递 children 的参数。具体实例如下
// children参数为字符串
type ChildrenPropsData {children: string;
};const ChildrenStringProps: React.FCChildrenPropsData (props) {return (divh2组件传递 children 参数实例/h2p{props.children}/p/div);
};// children参数为React.Node
type ChildrenReactNodePropsData {children: React.ReactNode;
};const ChildrenReactNodeProps: React.FCChildrenReactNodePropsData (props
) {return (divh2组件传递 children 参数实例/h2{props.children}/div);
};向组件传递事件和样式参数
这节主要是介绍一下在 React TS 中如何实现组件传递事件和样式参数。具体实例如下 事件参数实例 这里只是列举两个事件类型的传参实例每个事件在 Ts 中的声明可以参考如下信息
//
type EventPropsData {value: string;handleChange: (event: React.ChangeEventHTMLInputElement) void;getInputVal: (event: React.MouseEventHTMLButtonElement, id: string) void;
};const EventProps: React.FCEventPropsData ({value,handleChange,getInputVal,
}) {return (divh2组件传递 事件 参数实例/h2input typetext value{value} onChange{handleChange} /button onClick{(event) getInputVal(event, value)}Click/button/div);
};export default EventProps;样式参数实例
type StylePropsData {styles: React.CSSProperties;
};const StyleProps: React.FCStylePropsData ({ styles }) {return (divh2组件传递 样式 参数实例/h2div style{styles}这里是传入的参数样式/div/div);
};export default StyleProps;向组件中传入组件参数
这节主要是回顾组件传入的参数为组件时的 TS 写法。具体实例如下
// Profile.tsx
export type ProfileProps {name: string;
};export const Profile ({ name }: ProfileProps) {return divPrivate Profile component. Name is {name}/div;
};// Private.tsx
type PrivateProps {isLoggedIn: boolean;Component: React.ComponentTypeProfileProps; // 因为我们制定传入的组件需要带有一个name属性所以我们这里采用了TS的泛型来定义组件的参数
};export const Private ({ isLoggedIn, Component }: PrivateProps) {if (isLoggedIn) {return Component nameVishwas /;} else {return Login /;}
};