1

我搜索并将其与正确的解决方案进行比较,看起来没什么问题,但我几乎得到了如下所示的错误屏幕;

在此处输入图像描述

这里的导航代码有什么问题;

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import About from './app/components/About';

export default class Home extends Component {
  static navigationOptions = {
    title: 'Welcome',
  };
  navigateToAbout(){
    const { navigate } = this.props.navigation;
    navigate('About')
  }

  render() {

    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={()=>this.navigateToAbout()}>
          <Text>Go to About Page</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
const SimpleApp = StackNavigator({
  Home: { screen: Home },
  About: { screen: About },
});

AppRegistry.registerComponent('SimpleApp', () => SimpleApp);
4

2 回答 2

5

我认为您的代码很好,除非您必须绑定方法(通常我使用箭头函数,但如果您想在构造函数中绑定方法也可以),也许您可​​以这样尝试:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import About from './app/components/About';

export default class Home extends Component {
  static navigationOptions = {
    title: 'Welcome',
  }

  navigateToAbout = () => {
    this.props.navigation.navigate('About');
  }

  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={ this._navigateToAbout }
          <Text>Go to About Page</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
const SimpleApp = StackNavigator({
  Home: { screen: Home },
  About: { screen: About },
});

AppRegistry.registerComponent('SimpleApp', () => SimpleApp);

我希望它可以帮助你:)

于 2017-08-13T16:02:44.797 回答
1

您没有将主组件与导航连接,您应该将方法传递给navigation方法的mapDispatchToProps对象connect

这是一个例子:

import { connect } from 'react-redux'
import { NavigationActions } from 'react-navigation'

const navigate = NavigationActions.navigate

export class Home extends Component {
  static navigationOptions = ({ navigation }) => ({
    title: 'Welcome',
  })
  static propTypes = {
    navigate: T.func.isRequired,
  }

  navigateToAbout(){
    const { navigate } = this.props.navigation;
    navigate({ routeName: 'About' })
  }

  render() {

    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={()=>this.navigateToAbout()}>
          <Text>Go to About Page</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

export default connect(null, { navigate })(Home)
于 2017-08-12T23:25:24.293 回答