React Native-导航到屏幕-无效的挂钩调用

时间:2020-03-16 05:48:15

标签: android ios react-native react-native-android react-native-ios

App.js:

import React, { Component } from 'react';
import {View,Text} from 'react-native';
import { createDrawerNavigator } from 'react-navigation-drawer';
import {createAppContainer} from 'react-navigation';

import Epics from './screens/tmp';
import Pager from './screens/Pager';

const DrawerNavigator = createDrawerNavigator({
 Home: {screen: Epics},
 Page: {screen: Pager}
},{initialRouteName: 'Home'});

const Stack = createAppContainer(DrawerNavigator);

export default class App extends Component {
  render() {
    return <Stack />;
  }
}

尝试通过自定义组件导航到屏幕:

import { ActivityIndicator, Image, StyleSheet, View, TouchableHighlight } from 'react-native';
import PropTypes from 'prop-types';
import React from 'react';
import { useNavigation } from 'react-navigation-hooks';

import AuthorRow from './AuthorRow';

export default class Card extends React.Component {

  static propTypes = {
    fullname: PropTypes.string.isRequired,
    image: Image.propTypes.source.isRequired,
    linkText: PropTypes.string.isRequired,
    onPressLinkText: PropTypes.func.isRequired,
    epicId: PropTypes.string.isRequired,
  };

  state = {
    loading: true,
  };

  getNav(){
    return useNavigation();
  }

  handleLoad = () => {
    this.setState({ loading: false });
  };

  render() {
    const { fullname, image, linkText, onPressLinkText, epicId, prop } = this.props;
    const { loading } = this.state;
    
    return (
      <View>
        <AuthorRow
          fullname={fullname}
          linkText={linkText}
          onPressLinkText={onPressLinkText}
        />
        <TouchableHighlight onPress={() => this.getNav().navigate('Pager')} underlayColor="white">
          <View style={styles.image}>
            {loading && (
              <ActivityIndicator style={StyleSheet.absoluteFill} size={'large'} />
            )}
            <Image
              style={StyleSheet.absoluteFill}
              source={image}
              onLoad={this.handleLoad}
            />
          </View>
        </TouchableHighlight>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  image: {
    aspectRatio: 1,
    backgroundColor: 'rgba(0,0,0,0.02)',
  },
});

从以上代码中,尝试使用以下方法进行导航:

从“ react-navigation-hooks”导入{useNavigation};

getNav(){返回useNavigation(); }

this.getNav()。navigate('Pager')

它错误了我们的陈述:不变违反:无效的挂钩调用。挂钩只能在功能组件的主体内部调用。

如何使用“ useNavigation()”进行导航,或者如何在组件中获取“ this.props.navigation”引用? (我是React Native的新手,请帮助我理解)

更新

我尝试使用“ this.props.navigation”,它给了我未定义的错误: enter image description here

4 个答案:

答案 0 :(得分:2)

    //In Card component remove this
    //import { useNavigation } from 'react-navigation-hooks';

    //Add this line
    import {withNavigation} from 'react-navigation';

    class Card extends React.Component {

      static propTypes = {
        fullname: PropTypes.string.isRequired,
        image: Image.propTypes.source.isRequired,
        linkText: PropTypes.string.isRequired,
        onPressLinkText: PropTypes.func.isRequired,
        epicId: PropTypes.string.isRequired,
      };

      state = {
        loading: true,
      };

    //Remove this
    //  getNav(){
     //   return useNavigation();
      //}

      handleLoad = () => {
        this.setState({ loading: false });
      };

      render() {
        const { fullname, image, linkText, onPressLinkText, epicId, prop } = this.props;
        const { loading } = this.state;

        return (
          <View>
            <AuthorRow
              fullname={fullname}
              linkText={linkText}
              onPressLinkText={onPressLinkText}
            />
            <TouchableHighlight onPress={() =>  
//Make change like this
 this.props.navigation.navigate('Pager')} underlayColor="white">
              <View style={styles.image}>
                {loading && (
                  <ActivityIndicator style={StyleSheet.absoluteFill} size={'large'} />
                )}
                <Image
                  style={StyleSheet.absoluteFill}
                  source={image}
                  onLoad={this.handleLoad}
                />
              </View>
            </TouchableHighlight>
          </View>
        );
      }
    }

    const styles = StyleSheet.create({
      image: {
        aspectRatio: 1,
        backgroundColor: 'rgba(0,0,0,0.02)',
      },
    });
//Make change like this
    export default withNavigation(Card)

答案 1 :(得分:0)

您不能在类组件内部使用钩子将类组件转换为功能组件,也不能通过将导航道具传递给组件this.props.navigation.navigate('screenName')

来使用导航对象进行导航

答案 2 :(得分:0)

这是你的错误

错误

onPress = {()=> this.getNav()。navigate('Pager')

替换为

onPress = {()=> this.props.navigation.navigate('Pager')

这是示例

https://reactnavigation.org/docs/navigating/

https://medium.com/@marizu_makozi/navigating-between-screens-or-activities-using-react-navigation-library-68d57657d81

另一个示例代码

class FirstScreen extends React.Component {
  static navigationOptions = {
    title: 'First',
  }
  componentDidMount(){
    const {navigate} = this.props.navigation;
    navigate('Second');
    fetch('http://apiserver').then( (response) => {
      navigate('Second');
    });
  }
  render() {
    return (
      <AppLogo />
    );
  }
}

const AppNavigator = StackNavigator({
  First: {
    screen: FirstScreen,
  },
  Second: {
    screen: SecondScreen,
  },
});

答案 3 :(得分:0)

@sayog,您正在违反钩子兄弟的规则。 你可以试试这个吗?

const [loading, setLoading] = useState(false); const navigation = useNavigation();

确保在状态声明后放置

注意:不要为Hook使用类组件。使用功能组件进行钩子