React Native父子组件传方法报错:TypeError: undefined is not an object
React Native父子组件方法传递问题解决
问题原因
- 父组件传递方法错误:给子组件传
button_click时,直接执行了this.Follow(this.state.author),这会导致组件渲染时就调用该方法,传递给子组件的是方法执行后的返回值(这里Follow无返回值,所以是undefined),子组件自然无法识别有效函数。 - 子组件写法错误:
- 子组件是函数式组件,不存在组件实例,
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引用。 - 添加组件导出语句,确保父组件能正确导入使用。
- 直接解构父组件传递的所有props,无需用
内容的提问来源于stack exchange,提问作者Elly
相关产品推荐
相关产品推荐

