简体   繁体   中英

Getting data from a class component to Functional component - React Native

I'm pretty new to React Native and don't have the most experience with javascript so although this may be very simple I have no idea what to do. I have a class Component which acts like a popup in my app. It pops up on press of a touchable opacity and displays a little menu. I am trying to get the id of the button that is pressed on that menu and send it back to the functional component main screen (where the touchable opacity to open the menu is). I can get the id of the button but I'm struggling to get this data out of the popup and back into my main screen(functional component)

Here is my Code for the Main Screen:

import { StyleSheet, Text, View, Image,TouchableOpacity} from 'react-native'
import React,{useState} from 'react'
import tw, { create } from 'twrnc';
import Map from "../components/Map"
import { SafeAreaView } from 'react-native-safe-area-context';
import { BottomPopup } from '../components/popup';
import { selectTrucks} from '../slices/navSlice';
import { useSelector } from 'react-redux';


const Logistics = () => {
const Trucks = useSelector(selectTrucks);
let popupRef = React.createRef()
const onShowPopup = () => {
  popupRef.show()
}
const onClosePopup = () => {
  popupRef.close()
}
  return (
    <View style={{flex:1,resizeMode:'contain'}}>
    <View style={tw`h-12/16`}>
    <Map/>
    </View>
    <TouchableOpacity onPress={onShowPopup} style={{top:'-68%'}}>
    <Image
          source = {{uri: "https://icon-library.com/images/app-menu-icon/app-menu-icon-21.jpg" }}
          style = {{width:'20%', height:40,resizeMode:'contain'}}
    />
        <Text style={{color:'black',paddingLeft:2,fontSize: 26,fontWeight:"bold",top:-37,left:70}}>Truck {}</Text>
    </TouchableOpacity>
    <BottomPopup
    title = "Select Option"
    ref = {(target)=> popupRef = target}
    onTouchOutside={onClosePopup}
    data={Trucks.TrucksInfo}
   />
   <SafeAreaView style={{top:'-13%'}}>
   <Text style={{color:'darkgreen',paddingLeft:2,fontSize: 36,fontWeight:"bold"}}>123 Elmo Street</Text>
            <Text style={{color:'darkgreen',paddingLeft:2,fontSize: 24,fontWeight:"bold"}}>L4L 6L8, Mississauga, Ontario</Text>
            <Text style={{color:'darkgreen',paddingLeft:2,fontSize: 18,fontWeight:"bold"}}>Phone Number: 416-749-6857{'\n'}Client: Bobby Jeff{'\n'}Order Number: 7187181{'\n'}Packing Slip Number: 882929</Text>
            <Text style={{color:'black',fontSize: 18,paddingLeft:2}}>Customer Notified: Yes at 2:32 PM</Text>

   </SafeAreaView>
    </View>
  )
}

export default Logistics

const styles = StyleSheet.create({})

And Here is the code for the class component popup:

import { Modal,Dimensions,TouchableWithoutFeedback,StyleSheet,View,Text,FlatList,TouchableOpacity} from "react-native";
import React from "react";
import { useNavigation } from '@react-navigation/native';
import Logistics from "../screens/Logistics";

const deviceHeight = Dimensions.get('window').height

export class BottomPopup extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            show:false
        }
    }

    show = () => {
        this.setState({show:true})
    }
    close = () => {
        this.setState({show:false})
    }
    renderOutsideTouchable(onTouch) {
        const view = <View style = {{flex:1,width:'100%'}}/>
        if (!onTouch) return view

        return (
            <TouchableWithoutFeedback onPress={onTouch} style={{flex:1,width:'100%'}}>
                {view}
            </TouchableWithoutFeedback>
        )
    }
    renderTitle = () => {
        const {title} = this.props
        return (
            <View style={{alignItems:'center'}}>
            <Text style={{
                color:'#182E44',
                fontSize:25,
                fontWeight:'500',
                marginTop:15,
                marginBottom:30,
            }}>
                {title}
            </Text>
        </View>
        )
    }
    renderContent = () => {
       const {data} = this.props
        return (
            <View>
                <FlatList
                style = {{marginBottom:130}}
                showsVerticalScrollIndicator = {false}
                data={data}
                renderItem={this.renderItem}
                extraData={data}
                keyExtractor={(item,index)=>index.toString()}
                ItemSeparatorComponent={this.renderSeparator}
                contentContainerStyle={{
                paddingBottom:40
                }}
                />
            </View>
        )
    }
    
    renderItem = ({item}) => {
        return(
            <TouchableOpacity
            onPress={() => {this.close(),console.log(item.id)}}
            >
            <View style = {{height:50,flex:1,alignItems:'flex-start',justifyContent:'center',marginLeft:20}}>
                <Text style={{fontSize:18,fontWeight:'normal',color:"#182E44"}}>{item.name}</Text>
            </View>
            </TouchableOpacity>
        )
    }
    renderSeparator = () => {
        return(
        <View
        style={{
        opacity:0.1,
        backgroundColor:'#182E44',
        height:1
    }}
        />
        )
    }
    

    render() {

        let {show} = this.state
        const {onTouchOutside,title} = this.props
      return (
        <Modal
        animationType={"fade"}
        transparent={true}
        visible={show}
        onRequestClose={this.close}
        >
            <View style={{flex:1, backgroundColor:"#000000AA",justifyContent:'flex-end'}}>
                {this.renderOutsideTouchable(onTouchOutside)}
                <View style={{
                    backgroundColor:'#FFFFFF',
                    width:'100%',
                    paddingHorizontal:10,
                    maxHeight:deviceHeight*0.4}}
                    >
                    {this.renderTitle()}
                    {this.renderContent()}
                </View>
            </View>
        </Modal>
      )
    }
}

The console log in the render item function gets me the number i need i just need to get this number out and back into my logistics screen

What you can do is like onTouchOutside you can pass getId function as props which will return id .

I don`t have much experience with class component. So I have add sample code in functional component. You can refer this

const MainComponent = ()=>{
  const getIdFunc = (id)=>{
    //You will get id here
  }

  return(<View>
    {/* pass function here  */}
    <PopUpComponent getIdFunc={getIdFunc}/>
  </View>)
}

const PopUpComponent = (props)=>{
  return(<TouchableOpacity
    onPress={()=>{
      //call function by passing id here
      props.getIdFunc(id)
    }}
  >

  </TouchableOpacity>)
}

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.

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