How to move this.state from one screen to another screen with React Native

Asked

Viewed 3,828 times

1

Guys, I’m new to React Native, what I want to do is catch a this.state from screen 1 for example and use it on screen 2 to print that same this.state. I made a very grotesque example to try to explain:

import React, { Component } from 'react';
import {
    View,
    Text,
    StyleSheet,
    TextInput,
    TouchableHighlight,
} from 'react-native';

export default class Inputs extends Component {
    constructor(props) {
        super(props);

        this.state = {
            num1: 0,
            num2: 0,
            resultadoSoma: 0,
        };

        this.calcularSoma = this.calcularSoma.bind(this);
    }

    calcularSoma() {
        let calculoSoma = 0;

        calculoSoma = parseFloat(this.state.num1) + parseFloat(this.state.num2);

        let s = this.state;
        s.resultadoSoma = calculoSoma;
        this.setState(s);
    }

    render() {
        return (
            <View>
                <TextInput
                 onChangeText={num1 => {
                     this.setState({ num1 });
                 }}/>
                <TextInput
                 onChangeText={num2 => {
                     this.setState({ num2 });
                 }}/>
                <TouchableHighlight activeOpacity={0.3} onPress={this.calcularSoma}>
                    <Text style={styles.textoBotaoContinuar}>CALCULAR</Text>
                </TouchableHighlight>

                <Text>RESULTADO: {this.state.resultadoSoma}</Text>
           </View>
        );
    }
}

How do I catch this <Text>RESULTADO: {this.state.resultadoSoma}</Text> and show you screen 2?

Any help will be of great value.

1 answer

1


To pass data from one screen to another you can use the component React-Native-navigation achieving in a very simple way pass the values to the screen you want.

Example of use for this case

Using two components (screens). We would like to pass the state rescue of tela1 to the tela2

Component passing value(tela1):

this.props.navigation.navigate('tela2', {resultado: this.state.resutadoSoma})

Component receiving value(tela2):

this.props.navigation.state.params.resultado
  • 1

    I was able to pass the values from one screen to another using this React-Native-navigation feature. Thank you very much :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.