React Native useNavigation 类组件

lea*_*ner 7 react-native

我正在使用一个类组件,我想从这里导航到另一个屏幕。但它说导航未定义。我查阅了文档,意识到我需要使用userNavigationThis。但我不知道如何实际使用它。请有人帮忙

export default class ReduxScreen extends Component {
render() {
    return (
        <View>
           <Button block style={{ marginHorizontal: 30, marginTop: 50 }} onPress={() => {
         //I want to add the useNavigation here

            }}>
             <Text style={{ color: '#FFF' }}>Start</Text>
          </Button>
        </View>
    )
}}
Run Code Online (Sandbox Code Playgroud)

Wah*_*tar 5

useNavigation是一个钩子,钩子只能在这样的功能组件内部使用。

 const navigation = useNavigation()
Run Code Online (Sandbox Code Playgroud)

但是当您使用类组件时,您可以像这样导航。

this.props.navigation.navigate('YouScreen', {paramsIfAny})
Run Code Online (Sandbox Code Playgroud)

But you have to make sure that navigation prop is available在您的类组件中,console.log如果可用,则上面的行将起作用,如果不可用,则必须遵循此操作。

笔记:navigation prop is always available in the parent route(Route which is used to navigate some screen)

https://reactnavigation.org/docs/navigating-without-navigation-prop

另一个解决方案是您可以将导航属性从功能组件传递到这样的类组件。

export default function RootFunction (){
const navigation = useNavigation() // extract navigation prop here 

 return <ReduxScreen navigation={navigation} /> //pass to your component.

  }




class ReduxScreen extends Component {
  render () {
    return (
      <View>
        <Button block style={{ marginHorizontal: 30, marginTop: 50}}
          onPress={() => {
            this.props.navigation.navigate('YourScreen')
                  // now prop will be available here
          }}>
          <Text style={{ color: '#FFF' }}>Start</Text>
        </Button>
      </View>
    )
  }
}


 
Run Code Online (Sandbox Code Playgroud)


Mil*_*wal -3

如链接文档中所示,您必须使用functional组件才能使用导航挂钩。

尝试这个

import { useNavigation } from '@react-navigation/native';

export default () => {
  const navigation = useNavigation();

  return (
    <View>
      <Button
        block
        style={{ marginHorizontal: 30, marginTop: 50 }}
        onPress={() => navigation.navigate('YourScreenHere')}
      >
        <Text style={{ color: '#FFF' }}>Start</Text>
      </Button>
    </View>
  );
};

Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!