React函数组件传递函数prop调用时报Redirect is not a function错误如何解决
错误原因
- React函数组件不存在实例
this指向,调用时加this前缀属于错误写法 - 你将
Redirect的解构位置写错了:父组件是直接给Planet组件传递的Redirect属性,不属于planet属性内部的字段,但你在子组件参数里把Redirect写到了planet对象的嵌套解构中,自然取不到有效值,就会报不是函数的错误。
修复后的子组件代码
export default function Planet({ Redirect, planet: { color, xRadius, zRadius, size, speed, offset,Name = "",...props} }) { // 把Redirect放到外层props解构,不要放在planet的嵌套解构里 return ( <> <mesh ref={planetRef} onClick={(e) => { Redirect(); // 直接调用,不需要加this }}> <sphereGeometry args={[size, 32, 32]} /> <meshStandardMaterial color={color} /> {Name != "" && <Html prepend distanceFactor={65}> <div className="annotation">{Name}</div> </Html> } </mesh> <Eliptical xRadius={xRadius} zRadius={zRadius} /> </> ); }
补充建议
可以将prop名改为小驼峰redirect,和普通变量命名规范保持一致,避免和React内置的Redirect组件命名冲突。
内容的提问来源于stack exchange,提问作者user13652920
相关产品推荐
相关产品推荐

