如何获取更新后的值并将其应用于 React Native 中的另一个函数?

How to get the updated value and apply it to another function in React Native?

对于新手react native,我怎样才能从usestate获取更新后的值并将其应用于另一个函数?例如这是我的代码:

function HomeScreen({ navigation }) {
    return (
        <View style={styles.container}>
            <TouchableOpacity
                style={styles.scanButton}
                title="Scan"
                onPress={() => navigation.navigate("BarcodeScanner")}
            >
                <Text style={styles.scanText}>Scan</Text>
            </TouchableOpacity>
            <TextInput
                style={styles.input}
                placeholder="Barcode Value ... "
                // i want to put the updated value here in "value"
                value=""
            />
        </View>
    );
}
function BarcodeScanner() {
    const [barcodeData, setBarcodeData] = useState();

    const handleBarCodeScanned = ({ data }) => {
        setScanned(true);
        Alert.alert("Result", `Barcode data ${data} has been scanned!`, [
            {
                text: "Cancle",
                onPress: () => console.log("Cancle pressed"),
            },
            {
                text: "Apply",
              onPress: () => setBarcodeData(data),
            },
        ]);
        
    };

我已经尝试了几个小时,但没有找到解决方案,有什么建议吗?

我们可以使用 route paramsbarcodeData 传回 HomeScreen。实际上,从您提供的代码中,我们可以删除 BarcodeScanner 中的状态并直接在 handleBarCodeScanned 函数中传递 data

这可以按如下方式实现。我假设 HomeScreen 是在导航器中定义的 Screen

function BarcodeScanner() {
       const navigation = useNavigation()

        Alert.alert("Result", `Barcode data ${data} has been scanned!`, [
            {
                text: "Cancle",
                onPress: () => console.log("Cancle pressed"),
            },
            {
                text: "Apply",
              onPress: () => navigation.navigate("HomeScreen", {data: data}),
            },
        ]);
        
};

Homescreen中,我们处理状态。

function HomeScreen({ navigation, route }) {
    const [barcodeData, setBarcodeData] = useState();

    useEffect(() => {
         if (route.params) {
             setBarcodeData(route.params.data)
         }
    }, [route.params])
    return (
        <View style={styles.container}>
            <TouchableOpacity
                style={styles.scanButton}
                title="Scan"
                onPress={() => navigation.navigate("BarcodeScanner")}
            >
                <Text style={styles.scanText}>Scan</Text>
            </TouchableOpacity>
            <TextInput
                style={styles.input}
                placeholder="Barcode Value ... "
                value={barcodeData}
            />
        </View>
    );
}