3

我一直在尝试使用反应导航启动并运行,但是当我尝试将导航项移动到它们自己的组件中时遇到了问题。

HomeScreen.js

import React, { Component } from 'react';

import {
  StyleSheet,
  View,
  Text
} from 'react-native';

import NavButton from '../components/NavButton'

class HomeScreen extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>
        Hello World
        </Text>

        <NavButton
        navigate={this.props.navigator}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
});


export default HomeScreen;

然后在 NavButton 组件中,我尝试导航到新屏幕。

 class NavButton extends Component {
  render() {
    return (
      <View>
        <Button
        title="Go to About"
        onPress={() => this.props.navigator.navigate('About')}
        />
      </View>
    );
  }
}
export default NavButton;

但我不断收到错误“无法读取未定义的属性'导航'。

这也是我的 Router.js 文件。

import React from 'react';
import {StackNavigator} from 'react-navigation';

import HomeScreen from '../screens/HomeScreen'
import AboutScreen from '../screens/AboutScreen'


export const AppNavigator = StackNavigator({
  Home: {
    screen: HomeScreen
  },
  About: {
    screen: AboutScreen
  }
})
4

4 回答 4

7

如果您重命名navigate={this.props.navigator}navigator={this.props.navigation},它应该可以工作,因为您正在调用 NavButton this.props.navigator.navigate

于 2017-03-14T18:52:12.213 回答
0

非屏幕组件的普通组件默认不会接收到导航属性。

要解决此异常,您可以在从屏幕渲染时将导航道具传递给 NavButton,如下所示:<NavButton navigation={this.props.navigation} />

或者,我们可以使用该withNavigation功能自动提供导航道具


import { withNavigation } from 'react-navigation';

class NavButton extends React.Component {
  render() {
    return (
      <Button
        title="Back"
        onPress={() => {
          this.props.navigation.goBack();
        }}
      />
    );
  }
}

// withNavigation returns a component that wraps NavButton and passes in the
// navigation prop
export default withNavigation(NavButton);

参考:https ://reactnavigation.org/docs/en/connecting-navigation-prop.html

于 2019-10-16T13:09:46.733 回答
0
import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function GoToButton() {
  const navigation = useNavigation();

  return (
    <Button
      title='Screen Name'
      onPress={() => navigation.navigate(screenName)}
    />
  );
}

您可以将 @react-navigation/native 中的 useNavigation 与 React Navigation v 5.x 一起使用。文档中的更多详细信息。

于 2021-02-24T12:47:26.147 回答
0

确保你正在编译 ES6

如果不是简单地使用 this.props.navigation 或 this.props.navigation.navigate 任何你需要

于 2019-11-28T11:27:15.523 回答