繁体   English   中英

如何在“React Native 功能组件”中将“状态”从子级传递给父级?

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

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

我的主要目的是通过选择器打开一个输入字段。 所以现在我需要将 item.value (作为 state 'selectedValue')传递给父组件以提交。 我怎样才能将这个孩子 state 传递给父母 state?

这是我的子组件:

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;

这是我的父组件:

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,
  },
});

您不想将 state 从孩子传递给父母,而是想将它从父母传递给孩子。 您需要将 state 提升ComplaintSubmission并使用道具来控制ProductPicker

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM