【问题标题】:How to use React Navigation useNavigation Hook in a class component?如何在类组件中使用 React Navigation useNavigation Hook?
【发布时间】:2021-08-24 09:42:53
【问题描述】:

我是 react-native 的初学者。如何在 React 类组件中使用 useNavigation 挂钩?

【问题讨论】:

    标签: react-native react-navigation


    【解决方案1】:

    From Documentation - 您可以将类组件包装在函数组件中以使用钩子:

    class MyBackButton extends React.Component {
      render() {
        // Get it from props
        const { navigation } = this.props;
      }
    }
    
    // Wrap and export
    export default function(props) {
      const navigation = useNavigation();
    
      return <MyBackButton {...props} navigation={navigation} />;
    }
    
    

    【讨论】:

      【解决方案2】:

      useNavigation 是一个钩子,所以你应该在functional component 中使用它。一个简单的例子如下:

      import {useNavigation} from '@react-navigation/native';
      
      const SomeButton = () => {
        const navigation = useNavigation();
      
        return ( 
          <TouchableOpacity onPress={() => navigation.navigate('HomePage')}>
          </TouchableOpacity>
        )
      }
      

      通常您使用navigation 导航到任何其他screen,但当然它也支持很多其他高级功能

      【讨论】:

      • 如何在不传递navigation 作为道具的情况下从类组件导航?
      • 你不应该混淆它们,当你想使用useNavigation时,它是一个钩子,你应该在基于函数的组件中使用它,如果你需要在基于类的组件中导航,不要使用useNavigation
      猜你喜欢
      • 2020-05-22
      • 2020-11-29
      • 2021-10-14
      • 1970-01-01
      • 2022-12-19
      • 2021-11-12
      • 1970-01-01
      • 2020-08-30
      • 2021-06-19
      相关资源
      最近更新 更多