Передача пользовательского ввода со второго экрана на первый с помощью StackNavigator. - PullRequest
0 голосов
/ 31 августа 2018

В приложении это то, что я пытаюсь сделать.


На первом экране мне нужно отобразить введенное пользователем значение ввода текста на втором экране.

Передача данных на третий экран работает отлично, однако мне нужно значение из второго экрана на первом экране.

Ниже приведен пример кода: Закусочная ссылка

Проблема в том, что мне нужен какой-то способ скрыть {this.props.navigation.state.params.UserWeight}, пока значение не будет задано на втором экране и не отправлено обратно на первый экран, поэтому, возможно, мне нужен if / еще заявление? Я пробовал кое-что, но ничего не получается.

App.js

import React, { Component } from 'react';
import { StyleSheet, View, TouchableOpacity, Text } from 'react-native';
import { createStackNavigator } from 'react-navigation';
import AddWeightScreen from './AddWeight';

class TodayScreen extends Component {
  static navigationOptions =
    {
      title: 'Today'
    };

render() {

    return (
      <View style={styles.container}>
          <TouchableOpacity onPress={() => this.props.navigation.navigate('Weight')}>

            // if no weight entered (default) display this text
            <Text style={styles.textStyle}>
              Go to Add Weight screen
            </Text>

            // else when user weight has been entered on the next screen display the result on this screen
            // i'm commenting out the object below because it isn't defined here by default and it throws an error, it gets defined in the next screen but i need to display it here
            <Text style={styles.textStyle2}>
            Weight =
            {this.props.navigation.state.params.UserWeight}
            </Text>

          </TouchableOpacity>

      </View>
    );
  }
}

export const Project = createStackNavigator(
  {
    Today: TodayScreen,
    Weight: AddWeightScreen, 
  });

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    flex: 1,
    backgroundColor: 'white'
  },
  textStyle: {
    color: '#0066cc',
    textAlign: 'center',
    fontSize: 20, 
    marginTop: 40,
  },
    textStyle2: {
    color: 'black',
    textAlign: 'center',
    fontSize: 20, 
    marginTop: 40,
  },

});

export default Project;

AddWeight.js

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

class AddWeightScreen extends Component {
  static navigationOptions =
    {
      title: 'Add your Weight'
    };

  Send_Data_Function = () => {
    this.props.navigation.navigate('Today', {
      UserWeight: this.state.TextInput_Weight,
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput 
          style={styles.textInputStyle}
          placeholder="Enter your Weight"
          onChangeText={data => this.setState({ TextInput_Weight: data })} 
          autoFocus = {true}
          keyboardType={'numeric'}
        /> 

        <TouchableOpacity onPress={this.Send_Data_Function} style={styles.button} >
          <Text style={styles.buttonText}> Save </Text>
        </TouchableOpacity>
      </View>
    );
  }
}


const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    flex: 1,
    backgroundColor: 'white'
  },
  textInputStyle: {
    height: 30,
    width: '90%',
    borderWidth: 1,
    borderColor: 'gray',
    margin: 15,
    padding: 2
  },
  button: {
    width: '90%',
    height: 40,
    padding: 10,
    backgroundColor: '#0066cc',
  },
  buttonText: {
    color: '#fff',
    textAlign: 'center',
    fontWeight: '600'
  },
});

export default AddWeightScreen;

1 Ответ

0 голосов
/ 31 августа 2018

Вы можете просто условно показать текст, выполнив что-то вроде ниже. Вероятно, лучше всего сначала проверить, существует ли params, иначе он будет неопределенным

 {this.props.navigation.state.params && this.props.navigation.state.params.UserWeight && (<Text style={styles.textStyle2}>
   Weight = {this.props.navigation.state.params.UserWeight}
 </Text>)}
...