Search code examples
javascriptreact-nativereact-native-router-flux

How do I call my non static function from another class without making a new instance of class? - React Native Router Flux


I render a right bar button in the router file, when it is tapped I want to call a function from another class that saves the data. It can't be a static method because it needs to access "this" property. If I declare a new instance of the class it won't have a the correct data. So what am I supposed to do?

Navigation screen:

import React from 'react';
import {View, Text, TouchableOpacity} from 'react-native';
import { Router, Scene, Actions } from 'react-native-router-flux';

import NewUserScreen from './NewUserScreen';
import AddMealScreen from './AddMealScreen';

export default function App() {

  return (
   <Router>
     <Scene key="root">
      <Scene key="newUser"
      component={NewUserScreen}
      title="App"
      initial
      />
      <Scene
        key="addMeal"
        component={AddMealScreen}
        title="Add Meal"
        renderRightButton={() =>(
          <View>
            <TouchableOpacity onPress={() => AddMealScreen.saveMeal()}>
              <Text>Add</Text>
            </TouchableOpacity>
          </View>
        )}
        />
     </Scene>
    </Router>
  );
}

Add Meal Screen:

export default class AddMealScreen extends Component {

  constructor() {
    super();
    this.state={
      mealText: '',
    }
  }

  render() {
    return (
        <View style={styles.container}>
        <TextInput style = {styles.mealTextField} 
        placeholder = "Meal"
        onChangeText={(mealText) => this.setState({mealText})}
        />
        </View>
    );
 }

  saveMeal = async () => {
     await data.saveString('meal', this.state.mealText)
     await data.getStringData('meal');
 }

Solution

  • You can call child component function by using ref

    you are using functional component therefore, you have to use useRef hook

    Code:

    Navigation screen:

    import React, { Component, useRef } from "react";
    
    export default function App() {
      const _AddMealScreen = useRef();
    
      return (
        <Router>
          <Scene key="root">
            <Scene key="newUser" component={NewUserScreen} title="App" initial />
            <Scene
              initial
              key="addMeal"
              component={() => <AddMealScreen ref={_AddMealScreen} />}
              title="Add Meal"
              renderRightButton={() => (
                <View>
                  <TouchableOpacity
                    onPress={() => _AddMealScreen.current.saveMeal()}
                  >
                    <Text>Add</Text>
                  </TouchableOpacity>
                </View>
              )}
            />
          </Scene>
        </Router>
      );
    }