React Native中无法将函数作为props传递给子组件的问题
React Native路由中Props传递失败的问题分析与修复
问题重现
你在App.js里定义了App类组件并写了newalerter函数,尝试通过路由把这个函数传给SearchPageComp,但点击按钮时出现错误:undefined is not a function (evaluating '_this3.props.newalerter()')。你的代码大致是这样的:
class App extends React.Component { constructor() { super() this.state= { modalstuffshown: false, modalitems: null, } this.newalerter = this.newalerter.bind(this); } newalerter() { Alert.alert("hey") } } const MainScreenPage = () => ( <View> <TopMovies /> </View> ) const SearchPage = () => ( <View> <SearchPageComp newalerter={this.newalerter} /> </View> ) export const RootTabs = TabNavigator({ MSPage: { screen: MainScreenPage, }, SPage: { screen: SearchPage, }, }) export default RootTabs;
问题根源
其实有两个关键错误导致了这个问题:
- 你的
App类组件根本没被使用:你最后默认导出的是RootTabs,而App类只是被定义了,但从未被实例化渲染。这意味着App里的newalerter函数从来没有真正存在于任何活跃的组件实例中,自然无法被调用。 - 函数组件误用
this:SearchPage是一个函数式组件,函数组件内部没有this上下文,所以你写的this.newalerter本身就是undefined——这也是报错的直接原因。
修复方案
这里提供一个最直接的修复思路,让App作为根组件,把函数正确传递给路由页面:
import React, { Component } from 'react'; import { View, Alert } from 'react-native'; import { TabNavigator } from 'react-navigation'; // 注意导入对应版本的导航库 class App extends Component { constructor() { super() this.state= { modalstuffshown: false, modalitems: null, } this.newalerter = this.newalerter.bind(this); } newalerter() { Alert.alert("hey") } render() { // 在App组件内部定义路由,这样就能访问到this.newalerter const RootTabs = TabNavigator({ MSPage: { screen: MainScreenPage, }, SPage: { // 用一个匿名组件包裹SearchPage,把newalerter传进去 screen: (props) => <SearchPage newalerter={this.newalerter} {...props} />, }, }); return <RootTabs />; } } const MainScreenPage = () => ( <View> <TopMovies /> </View> ) // SearchPage作为函数组件,通过参数解构接收newalerter const SearchPage = ({ newalerter, ...restProps }) => ( <View> <SearchPageComp newalerter={newalerter} {...restProps} /> </View> ) // 现在默认导出App组件,让它成为应用的根组件 export default App;
修复说明
- 现在
App作为根组件被导出,它会被实例化,newalerter函数也会绑定到正确的组件实例上。 - 在定义
SPage的屏幕时,我们用一个匿名组件包裹SearchPage,把this.newalerter作为props传递进去,同时保留路由自带的props(比如导航相关的属性)。 SearchPage作为函数组件,通过参数解构接收newalerter,再把它传递给SearchPageComp,这样子组件就能正确调用这个函数了。
如果你的项目使用的是React Navigation 5+(函数式导航API),思路类似,只是路由定义方式会有所不同,但核心都是确保函数所在的组件被正确实例化,并且props传递路径正确。
内容的提问来源于stack exchange,提问作者craftdeer
相关产品推荐
相关产品推荐

