簡體   English   中英

我如何將數據從屏幕上傳遞到 React Native 中的另一個?

[英]How would I pass data from on screen to another in React Native?

我在嘗試將一些數據傳遞到另一個屏幕時遇到問題。 當前使用useState鈎子,我想在下一個屏幕上使用該值。

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;

我想將num值帶到下一個屏幕,我嘗試使用navigation.navigate發送值,然后嘗試使用 getParam 但這不起作用。

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;

任何幫助將非常感激!

當Screens之間發生路由時,那么可以通過以下代碼獲取CalcScreen組件中的num值:

function CalcScreen({ navigation, route }) {
  const { num } = route.params;
  1. 通過將參數作為第二個參數放入一個對象中,將參數傳遞給路由,作為來自 First Screen 的 navigation.navigate 函數。 使用 :

    this.props.navigation.navigate('RouteName', { /* params go here */ })

  2. 閱讀第二個屏幕中的參數。 使用:

    this.props.navigation.getParam(paramName, defaultValue)

這是完整的工作示例, 鏈接

使用props在 react native 中,我們使用 props 將數據從一個類傳遞到另一個類或從一個頁面傳遞到另一個類。

https://reactnative.dev/docs/props

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM