我是React Native新手。我尝试做的是将react navigation添加到我的登录页面,用户可以点击按钮并导航到注册页面,但我收到错误Cannot read property 'navigate' of Undefined
。我已经通过互联网搜索了解决方案,但没有运气。这对我没有帮助 - React Navigation - cannot read property 'navigate' of undefined和其他人一样。
这是我的代码
index.ios.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import {StackNavigator} from 'react-navigation';
import Login from './src/screens/Login';
import Signup from './src/screens/Signup';
export default class tapak extends Component {
constructor(props) {
super(props);
this.buttonPress = this.buttonPress.bind(this);
}
render() {
return (
<View style={styles.container}>
<Text style={{color: 'blue'}} onPress={this.buttonPress}>sign up</Text>
</View>
);
}
buttonPress() {
console.log('called');
this.props.navigation.navigate('Signup');
}
}
const Stacks = StackNavigator({
Login: {
screen: Login
},
Signup:{
screen: Signup
}
});
答案 0 :(得分:3)
只需在 index.ios.js 中简单渲染StackNavigator,然后将按钮移至登录组件:
const Stacks = StackNavigator({
Login: {
screen: Login
},
Signup:{
screen: Signup
}
});
class tapak extends Component {
render() {
return (
<Stacks />
);
}
}
Login.js:
export default class Login extends Component {
constructor(props) {
super(props);
this.buttonPress = this.buttonPress.bind(this);
}
buttonPress() {
console.log('called');
this.props.navigation.navigate('Signup');
}
render() {
return (
<View style={styles.container}>
<Text style={{color: 'blue'}} onPress={this.buttonPress}>sign up</Text>
</View>
);
}
}
简单的工作示例 here
答案 1 :(得分:1)
将此代码写入index.ios.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import {StackNavigator} from 'react-navigation';
import Login from './src/screens/Login';
import Signup from './src/screens/Signup';
const Stacks = StackNavigator({
Login: {
screen: Login
},
Signup:{
screen: Signup
}
});
Login.js
import React ,{Component} from 'react';
import {
Text, View , Button,Image,
} from 'react-native';
export default class HomeScreen extends Component {
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text
onPress={() => navigate('Signup')}
> SignUp</Text>
</View>
);
}
}
希望这对你有所帮助。
答案 2 :(得分:0)
这个问题的唯一答案是将const {navigation} = this.props.navigation放在render()函数中,然后可以在所需的任何组件中使用它
例如
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>This is the home screen of the app</Text>
<Button
onPress={() => navigate('Profile', { name: 'Brent' })}
title="Go to Brent's profile"
/>
</View>
);
}
请阅读https://reactnavigation.org/docs/en/navigation-prop.html的这份文档
答案 3 :(得分:-1)
我认为您需要包含navigationOptions
,例如:
class MyComponent extends React.Component {
static navigationOptions = {
title: 'Great',
// other configurations
}
render() {
return (
// your view
)
}
}
此外,您需要确保使用AppRegistry.registerComponent('glfm', () => Stacks);
而不是AppRegistry.registerComponent('glfm', () => tapak);