Как передать значение между страницами React Native

Я очень новичок в том, чтобы реагировать на родной язык, и я пытаюсь передать два входа между двумя страницами, нажав кнопку, но я не уверен, где я ошибаюсь. Мое намерение состоит в том, чтобы одна переменная была «название книги», а вторая - «количество страниц». Любая помощь будет очень признательна.

Страница 1

const FirstPage = ({navigation}) => {
  const [userName, setUserName] = useState('');
    return (
        <SafeAreaView style = {{flex: 1}}>
          <View style = {styles.container}>
            <Text style = {styles.heading}>
              React Native Pass Value From One Screen to Another
              Using React Navigation
            </Text>
            <Text style = {styles.textStyle}>
              Please insert your name to pass it to second screen
            </Text>
            {/*Input to get the value from the user*/}
            <TextInput
              value = {String}
              onChangeText = {(bookname) => setUserName(bookname)}
              placeholder = {'Enter Any value'}
              style = {styles.inputStyle}
            />
            
            <TextInput
              value = {String}
              onChangeText = {(pagenum) => setUserName(pagenum)}
              placeholder = {'Enter Any value'}
              style = {styles.inputStyle}
            />
            <Button
              title = "Go Next"
              //Button Title
              onPress = {() =>
                navigation.navigate('SecondPage', {
                  paramKey: pageNum,
                  paramKey: bookName,
                })
              }
            />

Страница 2

const SecondPage = ({route}) => {
  return (
    <SafeAreaView style = {{flex: 1}}>
      <View style = {styles.container}>
        <Text style = {styles.heading}>
          React Native Pass Value From One Screen to Another
          Using React Navigation
        </Text>
        <Text style = {styles.textStyle}>
          Values passed from First page: {route.params.paramKey}
        </Text>
      </View>
    
    </SafeAreaView>
  );
};

Взгляните на документацию: reactnavigation.org/docs/params.

user18309290 26.10.2022 16:53
0
1
95
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

    <Button
      title = "Go Next"
      //Button Title
      onPress = {() =>
        navigation.navigate('SecondPage', {
          paramKey: pageNum,
          paramKey: bookName,
        })
      }
    />

Вы можете использовать сокращение:

    <Button
      title = "Go Next"
      //Button Title
      onPress = {() =>
        navigation.navigate('SecondPage', {
          pageNum, // same like pageNum: pageNum
          bookName,//           bookName: bookName
        })
      }
    />

Параметры доступа:

 const SecondPage = ({route}) => {
  return (
    <SafeAreaView style = {{flex: 1}}>
      <View style = {styles.container}>
        <Text style = {styles.heading}>
          React Native Pass Value From One Screen to Another
          Using React Navigation
        </Text>
        <Text style = {styles.textStyle}>
          Values passed from First page: {route.params.pageNum}
        </Text>

        <Text style = {styles.textStyle}>
          Values passed from First page: {route.params.bookName}
        </Text>
      </View>
    
    </SafeAreaView>
  );
};

Я продолжаю получать сообщение об ошибке "Не удается найти переменную: pageNum"

TevovoChin 26.10.2022 16:48
Ответ принят как подходящий

Здесь вы можете найти полный пример

import * as React from 'react';
import { Pressable, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import {
  createStackNavigator,
  HeaderBackButton,
} from '@react-navigation/stack';
import { useNavigation, useRoute } from '@react-navigation/native';

function ScreenOne() {
  const navigation = useNavigation();
  const route = useRoute();

  return (
    <View style = {{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Screen {route?.params?.passedValue}</Text>
      <Pressable
        onPress = {() => navigation.navigate('Two', { passedValue: 'Two : 2'})}
        style = {{ backgroundColor: 'plum', padding: 10 }}>
        <Text>Navigate an pass</Text>
      </Pressable>
    </View>
  );
}


const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name = "One" component = {ScreenOne} />
        <Stack.Screen name = "Two" component = {ScreenOne} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Другие вопросы по теме