React Native类父组件内部函数式子组件传参报错排查
问题原因与解决方案
错误原因
你犯了ES6类语法的基础错误:类组件的类体内部不能直接用const声明变量/函数组件。虽然第一种写法没报错(可能是编译环境的宽松处理),但这本身不符合类语法规范,当你嵌套调用GenericChild时,这个语法问题就触发了Cannot read properties of undefined (reading 'apply')的报错。
正确写法方案
方案1:把子组件移到类外部(推荐)
把通用子组件和具体子组件都放在Parent类外面,通过props传递需要的a和b,代码结构更清晰,也符合组件拆分的原则:
import { Component, View } from 'react-native'; const GenericChild = ({ a, b, c }) => { return <View a={a} b={b} c={c} />; }; const ChildA = (props) => { return <GenericChild {...props} c={101} />; }; const ChildB = (props) => { return <GenericChild {...props} c={102} />; }; class Parent extends Component { render() { return ( <> <ChildA a={this.props.a} b={this.props.b} /> <ChildB a={this.props.a} b={this.props.b} /> </> ); } }
方案2:在render方法内部定义子组件
如果必须在类内部定义,可以把这些函数组件放在render方法里——因为render是类的方法,内部允许用const声明变量:
class Parent extends Component { render() { const GenericChild = (props) => { return <View a={this.props.a} b={this.props.b} c={props.c} />; }; const ChildA = () => { return <GenericChild c={101} />; }; const ChildB = () => { return <GenericChild c={102} />; }; return ( <> <ChildA /> <ChildB /> </> ); } }
方案3:使用类属性定义(需编译支持)
如果你的项目配置了支持类字段语法(比如Babel的@babel/plugin-proposal-class-properties),可以去掉const,直接把组件赋值给类属性:
class Parent extends Component { GenericChild = (props) => { return <View a={this.props.a} b={this.props.b} c={props.c} />; }; ChildA = () => { return <this.GenericChild c={101} />; }; ChildB = () => { return <this.GenericChild c={102} />; }; render() { return ( <> <this.ChildA /> <this.ChildB /> </> ); } }
内容的提问来源于stack exchange,提问作者gkeenley
相关产品推荐
相关产品推荐

