I am having trouble trying to pass some data to another screen. Currently using the useState
hook and I would like to use the value on the next screen.
NumScreen.JS:
import React, { useState } from "react";
import { Text, TextInput, Button, View, StyleSheet, TouchableOpacity } from "react-native";
function NumScreen({ navigation }) {
const [num, setNum] = useState("0");
const pressHandler1 = () => {
navigation.navigate("CalcScreen", { num });
}
const Separator = () => (
<View style={styles.separator} />
);
return (
<View style={styles.container}>
<Text>Enter Number of People:</Text>
<TextInput
returnKeyType="done"
keyboardType="numeric"
style={styles.input}
placeholder="e.g. 3"
onChangeText={(val) => setNum(val)}
/>
<Text> Number: {num} </Text>
<Separator />
<TouchableOpacity onPress={pressHandler1}>
<Text style={styles.button}>Submit</Text>
</TouchableOpacity>
</View>
);
}
export default NumScreen;
I want to get the num value to the next screen, I tried sending the value using navigation.navigate
then tried to use getParam but this did not work.
import React, { useState } from 'react';
import { Text, TextInput, Button, View, StyleSheet, TouchableOpacity } from "react-native";
function CalcScreen({ navigation }) {
const [tot, setTot] = useState("0");
const ppl = navigation.getParam(num);
const Separator = () => (
<View style={styles.separator} />
);
return (
<View style={styles.container}>
<Text> num: {ppl} </Text>
<Text>Enter Total Amount:</Text>
<TextInput
returnKeyType="done"
keyboardType="numeric"
style={styles.input}
placeholder="e.g. 5.50"
onChangeText={(val1) => setTot(val1)}
/>
<Text> Total: {tot} </Text>
</View>
);
}
export default CalcScreen;
Any help would be much appreciated!
When the routing between Screens happens, then you can get the num value in the CalcScreen
component by the following code:
function CalcScreen({ navigation, route }) {
const { num } = route.params;
Pass params to a route by putting them in an object as a second parameter to the navigation.navigate function from First Screen. Using :
this.props.navigation.navigate('RouteName', { /* params go here */ })
Read the params in your Second screen. Using:
this.props.navigation.getParam(paramName, defaultValue)
here is the complete working example, link
Using props We use props to pass data from one class to another or from one page to another in react native.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.