如何将 'State' 从 child 传递到 'React Native Functional Component' 中的 parent?

How to pass 'State' from child to parent in 'React Native Functional Component'?

我创建了一个选择器组件以从 API 获取数据并将其(ProductNames)显示在选择器列表中,select 其中之一。然后我能够将选择器项目值作为 productID。之后,我在 parent 组件中使用这个 child 组件,它表示要提交的表单。现在我可以在 parent 组件(表单)中看到选择器,我可以 select 其中之一。

我的主要目的是通过选择器打开一个输入字段。所以现在我需要将 item.value(作为状态 'selectedValue')传递给 parent 组件进行提交。如何将此 child 状态传递到 parent 状态?

这是我的 child 组件:

import React, {useEffect, useState} from 'react';
import {View, StyleSheet} from 'react-native';
import {Picker} from '@react-native-picker/picker';
import AsyncStorage from '@react-native-community/async-storage';


const ProductPicker = () => {
    const [selectedValue, setSelectedValue] = useState('');
    const [productDetails, setproductDetails] = useState([]);
console.log('selected value', selectedValue);
    useEffect(() => {
        getProductList();
    }, []);

    const getProductList = async () => {
        const token = await AsyncStorage.getItem('userToken');
        

        fetch('http://10.0.2.2:3000/customer/get-all-products', {

            method: 'post',
            headers: {
                'Content-Type': 'application/json',
                'Authentication': `Bearer ${token}`,
            },
        })
            .then((response) => response.json())
            .then((json) => setproductDetails(json.data))
            .catch((error) => console.error(error));

    };

    return (
        <View style={styles.container}>
            <Picker
                selectedValue={selectedValue}
                style={{height: 40, width: 150}}
                onValueChange={(itemValue, itemIndex) => {
                    setSelectedValue(itemValue);
                }}
            >

     

                {productDetails.map((item, index) => {
                    return (
                        <Picker.Item label={item.productName} value={item.productID} key={index}/>);
                })}

            </Picker>

        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: 40,
        alignItems: 'center',
    },
});

export default ProductPicker;

这是我的 parent 组件:

import * as React from 'react';
import {Button, View, Text, ScrollView, StyleSheet, Alert} from 'react-native';
import {Appbar} from 'react-native-paper';
import {TextInput, HelperText} from 'react-native-paper';
import {useEffect, useState} from 'react';
import AsyncStorage from '@react-native-community/async-storage';
import ProductPicker from './ProductPicker';


const ComplaintSubmission = ({navigation}) => {

    const [productID , setproductID] = useState('');
    const [description , setdescription] = useState('');
    const [token, setToken] = useState('');
    


    const saveToken = async () => {
        const token = await AsyncStorage.getItem('userToken');
        console.log('token from storage', token);
        setToken(token);
    }

    useEffect(() => {
        saveToken();
        fetch("http://10.0.2.2:3000/customer/lodge-complaint", {

            method: "post",
            headers: {
                'Content-Type': 'application/json',
                'Authentication': `Bearer ${token}`
            },
            body: JSON.stringify({

                description : description,
            })

        })

    }, []);


    const openAlert = () => {
        Alert.alert(
            "Complaint Successfully Submitted",
            "We review it as soon as possible. Thank you for reaching for us!",
            [{
                text: "OK",
                onPress : () => navigation.navigate("DashboardDrawer" ),

            }]


        );
    }

  return (
    <ScrollView>
      <Appbar.Header>
        <Appbar.BackAction onPress={() => navigation.goBack()} />
        <Appbar.Content title="Submit Complaint" />
        <Appbar.Action icon="magnify" onPress={() => navigation.openDrawer()} />
      </Appbar.Header>
      <Text>Plese Fill the following</Text>
      <View>
         

       <ProductPicker />

        <HelperText type="info">
          Make sure select the correct Product
        </HelperText>
      </View>

      <TextInput
        style={styles.PIDstyle}
        label="Description"
        onChangeText = {(description) => setdescription(description)}
      />
      <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>This is submittion</Text>
        <Button onPress={() => openAlert()} title="Submit Complaint" />
      </View>
    </ScrollView>
  );
};
export default ComplaintSubmission;
const styles = StyleSheet.create({
  PIDstyle: {
    marginTop: 30,
    marginLeft: 10,
    marginRight: 10,
  },
});

您不想将状态从子级传递给父级,而是想将状态从父级传递给子级。需要lift the state upComplaintSubmission,用道具控制ProductPicker

ComplaintSubmission 中,使用当前的 productId 调用 ProductPicker 并回调以更新它。

<ProductPicker productID={productID} setproductID={setproductID} />

现在ProductPicker有这些道具了。它应该使用它们而不是您现在可以删除的本地状态 selectedValue

const ProductPicker = ({productID, setproductID}) => {
<Picker
    selectedValue={productID}
    style={{height: 40, width: 150}}
    onValueChange={(itemValue, itemIndex) => {
        setproductID(itemValue);
    }}
>