React 中函数作为 Props 传递的 3 大误区与正确姿势

在react组件开发中,父组件向子组件传递数据或行为(函数)是常见的模式。typescript的引入为这种传递提供了强大的类型检查,帮助我们在开发阶段捕获潜在错误。然而,一个常见的误区是错误地使用javascript的对象展开运算符(spread operator)来传递单个函数prop,这通常会导致运行时undefined错误和typescript的类型检查报错。
理解问题:函数Prop为何会变成undefined?
当你在父组件中尝试以{...onDirectionsPress}的形式传递一个名为onDirectionsPress的函数给子组件时,你可能会发现子组件接收到的onDirectionsPress是undefined,并且TypeScript会抛出类似Function is missing in type but required in type 'Props'的错误。
让我们通过一个具体的例子来分析这个问题。
类型定义与组件结构:
假设我们有一个MapComponent组件,它期望接收一个名为onDirectionsPress的函数作为prop,以及其他一些数据prop。
// 定义MapComponent的Props类型
type SearchResult = {
id: string;
name: string;
latitude: number;
longitude: number;
};
type MapComponentProps = {
results: SearchResult[];
onDirectionsPress: (
latitude: number,
longitude: number,
sitename: string,
) => void;
};
// MapComponent组件定义
const MapComponent = ({ results, onDirectionsPress }: MapComponentProps) => {
// 在这里,onDirectionsPress 可能会是 undefined
console.log('MapComponent接收到的函数:', onDirectionsPress);
return (
{/* ... 其他地图相关内容 */}
{/* 假设某个地方会调用 onDirectionsPress */}
);
};
export default MapComponent;
1、本站目前拥有近 1000+ 精品收费资源,现在加入VIP会员即可全部下载。
2、本资源部分来源其他付费资源平台或互联网收集,如有侵权请联系及时处理。
欧迪资源网 » React 中函数作为 Props 传递的 3 大误区与正确姿势
2、本资源部分来源其他付费资源平台或互联网收集,如有侵权请联系及时处理。
欧迪资源网 » React 中函数作为 Props 传递的 3 大误区与正确姿势

发表评论