在React Native Navigation中,如何将道具发送到屏幕?

时间:2020-10-01 01:50:55

标签: javascript reactjs react-native react-navigation react-navigation-v5

我希望能够在除第一个屏幕之外的其他屏幕上使用导航,但是我收到一个错误,提示this.props不存在。

我的App.js文件设置如下:

import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';

import Screen2 from './screens/Screen2';  
import Screen3 from './screens/Screen3';
import HomeScreen from './screens/HomeScreen';

const Stack = createStackNavigator();

function HomeScreen({ navigation }) {
  return (
    <View>
        <Button
        title="Go to Screen2"
        onPress={() => {
        navigation.navigate('Screen2');
        }}
      />
      <Button
        title="Go to Screen3"
        onPress={() => {
        navigation.navigate('Screen3');
        }}
      />
    </View>
  );


const App: () => React$Node = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Screen2" component={Screen2} />
        <Stack.Screen name="Screen3" component={Screen3} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

app.js中的按钮可以工作,但是如果我转到Screen2并单击打算转到另一个按钮(在下面的示例中为Screen3),则道具不存在。

Screen2.js示例如下所示:

const Screen2: () => React$Node = () => {

  return (
    <>   
      <View style={{ flex: 1 }}>
        <Button
        title="Go to Screen3"
        onPress={goToScreen3}}
      />
      </View>     
    </>
  );

function goToScreen3() {
  if(condition){
this.props.navigate.navigate('Screen3');
}}

如何传递道具,以便可以在第二个屏幕中使用导航?

2 个答案:

答案 0 :(得分:0)

在功能组件中没有此绑定,因此您需要先从函数中获取道具

检查

const Screen2 = (props) => {

  return (
    <>   
      <View style={{ flex: 1 }}>
        <Button
        title="Go to Screen3"
        onPress={goToScreen3}}
      />
      </View>     
    </>
  );

function goToScreen3() {
  if(condition){
   props.navigate.navigate('Screen3');
  }
}
}

答案 1 :(得分:0)

对于功能组件,有时通过道具传递导航也很棘手。因此,只需使用withNavigation。

您必须导入它并用它包装函数。

import { withNavigation } from 'react-navigation';

const Screen2 = props => {

  const goToScreen3 = () => {
    if(condition){
    props.navigate.navigate('Screen3');
  }}

  return (
    <>   
      <View style={{ flex: 1 }}>
        <Button
        title="Go to Screen3"
        onPress={goToScreen3()}
      />
      </View>     
    </>
  );



export default withNavigation(Screen2)