react-native - 未定义不是对象“this2.props.navigation.navigate”
问题描述
我无法在另一个页面上导航。我在这个类中有默认类代码,导航工作正常
export default class ClassName1 extends React.Component {
constructor(props) {
super(props);
}
}
但是当我调用this.props.navigation
下面的类时它会抛出一个错误
class ClassName2 extends React.Component {
constructor(props) {
super(props);
}
}
像这样我在调用函数ClassName2
<TouchableOpacity onPress={() => this.props.navigation.navigate("Report") }>
<Text style={style.modalContainerText}>
inappropriate Content
</Text>
</TouchableOpacity>
两个类都在一个文件中。
解决方案
如果您的类包含在StackNavigator
函数中,您将可以访问,this.props.navigation
否则您必须使用withNavigation
如下函数
使用示例StackNavigator
import React, { Component } from 'react';
import { Button } from 'react-native';
import { StackNavigator } from 'react-navigation';
export class ClassName2 extends Component {
render() {
return <Button title="This will work" onPress={() => { this.props.navigation.navigate('someScreen') }} />;
}
}
export const myStackNavigator = StackNavigator({
myScreen: ClassName2
})
使用示例withNavigation
import React, { Component } from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';
class ClassName2 extends Component {
render() {
return <Button title="This will work" onPress={() => { this.props.navigation.navigate('someScreen') }} />;
}
}
export default withNavigation(ClassName2);
推荐阅读
- html - 有没有办法让这个按钮动画?
- sftp - 使用 Pentaho 从远程 SFTP 删除超过 7 天的文件
- cakephp - CakePHP在最后一页输出多余的分页链接
- javascript - 我如何获取类似于数据库中字段的值?
- node.js - 是否可以更改 jsdom 中的 HTML 标识符标签?
- powershell - 从域中的远程机器获取服务
- hive-metastore - 在负载均衡器后面的 ec2 机器中创建外部配置单元元存储
- html - 解码包含 HTML 的 json
- javascript - 如何将弧度应用于多个调整大小的拖动处理程序
- c# - 如何让 Microsoft PIA 在 Office 365 上的 Visual Studio for Excel 中成为可用参考?