You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native父子组件传方法报错:TypeError: undefined is not an object

React Native父子组件方法传递问题解决

问题原因

  1. 父组件传递方法错误:给子组件传button_click时,直接执行了this.Follow(this.state.author),这会导致组件渲染时就调用该方法,传递给子组件的是方法执行后的返回值(这里Follow无返回值,所以是undefined),子组件自然无法识别有效函数。
  2. 子组件写法错误:
    • 子组件是函数式组件,不存在组件实例,this为undefined,调用this.calc()必然报错。
    • 子组件解构props时只取了text,未解构uid和button_click,就算父组件传了这两个属性,子组件也无法访问。
    • 外部定义的calc函数无法获取子组件props,写法完全错误。

修复后的代码

父组件

import Child from "./Child";
import { View, StyleSheet } from 'react-native';

export default class Parent extends Component {
  constructor(props){
    super(props); 
    this.state={ author:"Helen"}
  } 

  Follow(uid){
    console.log("ok button pressed, uid:", uid)
  }  

  render(){
    return(
      <View style={styles.button}>
        <Child 
          text={"Follow"} 
          uid={this.state.author} 
          button_click={() => this.Follow(this.state.author)}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  button: {
    // 补充你的样式定义
  }
});

子组件

import { TouchableOpacity, Text, StyleSheet } from 'react-native';

const Child = ({ text, uid, button_click }) => {
  return (
    <TouchableOpacity style={styles.button} onPress={() => button_click(uid)}>
      <Text style={styles.text}>{text}</Text>
    </TouchableOpacity>
  );
};

export default Child;

const styles = StyleSheet.create({
  button: {
    // 补充你的样式定义
  },
  text: {
    // 补充你的样式定义
  }
});

关键修复点说明

  • 父组件:用箭头函数包裹Follow调用,确保传递给子组件的是函数引用,只有按钮点击时才会执行Follow方法。
  • 子组件:
    • 直接解构父组件传递的所有props,无需用this.props访问。
    • 在onPress中直接调用传入的button_click函数并传递uid参数,去掉错误的calc函数和this引用。
    • 添加组件导出语句,确保父组件能正确导入使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:27:39