You need to enable JavaScript to run this app. React Native跨组件传函数报错theFun.theFun不是函数怎么办
优惠活动
大模型
产品
解决方案
定价
更多

React Native跨组件传函数报错theFun.theFun不是函数怎么办

React Native 跨组件传函数报错修复

核心问题根源

  • 函数组件 props 接收规则错误
    React 函数组件的第一个形参是所有 props 汇总成的单个对象,不会按形参顺序拆分接收。你当前写的 function ModalPurpleCard(theList:any, theFun:any ) 存在两个问题:
    • 你把整个 props 对象命名为 theList,所以之前写的 theList.theList[0] 其实是取 props 里的 theList 属性,属于歪打正着能用
    • 第二个形参 theFun 不是 props 的属性,而是 React 预留的 ref 入参,默认就是 undefined,后续访问 theFun.theFun 必然报 undefined
  • TouchableOpacity 事件绑定错误
    onPress 需要传入未执行的函数引用,你写的 theFun.theFun("2","1","blueShrimp") 会在组件渲染时就立刻执行,不会等待用户点击触发。
  • 传函数 props 写法错误
    你之前尝试的 theFun={storeMeasurement("2","1","blueShrimp")} 是把 storeMeasurement 的执行返回值传给子组件,不是传函数本身,除非 storeMeasurement 主动返回一个函数,否则传过去的一定不是可执行函数。

修正后可直接运行的代码

父组件调用处

传函数 props 时不要加括号,否则会直接执行函数取返回值:

<ModalPurpleCard 
  theList={["10","91","thermometer"]}  
  theFun={storeMeasurement} 
/>

子组件定义处

直接从 props 对象里解构需要的属性,事件用箭头函数包裹延迟执行:

// 直接解构 props 里的 theList、theFun,不需要嵌套
function ModalPurpleCard({ theList, theFun }: any) {
  const [visOpen, setVisOpen] = React.useState(true);
  const [stillLoad, setStillLoad] = React.useState(true);

  const theFig = Number(theList[0]) + Number(theList[1])
  console.log(theFig)

  if (visOpen) {
    return (
      <TouchableOpacity onPress={()=> setVisOpen(false)}>
        <View style={{zIndex:3}}>
          <ModalSecCard>
            <Text style={{color:"#fff"}}>{theList[2]}</Text>
          </ModalSecCard>
        </View>
      </TouchableOpacity>
    )
  } else {
    if (stillLoad) {
      return (
        <TouchableOpacity 
          // 箭头函数包裹,点击时才执行调用逻辑
          onPress={() => theFun("2","1","blueShrimp")}
        >
          <ActivityIndicator animating={true} color="#333366"/>
        </TouchableOpacity>
      )
    } else {
      return <Text>{theFig}</Text>
    }
  }
}

特殊需求说明

如果你确实需要保留 theFun.theFun 的调用写法(比如要打包多个函数/属性成对象传递),调整方式如下:

  1. 父组件传参时把函数放到对象里:theFun={{ theFun: storeMeasurement }}
  2. 子组件调用时直接从 props 取:onPress={() => props.theFun.theFun("2","1","blueShrimp")}
    常规场景不建议这么写,平铺 props 更易维护

内容的提问来源于stack exchange,提问作者not_overrated

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.25 08:15:05