Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

reactjs - Switching between pages in React-native also return information

I can't send value to another page. locID, tourInfo, userName, userEmail I want to send this value. But I'm new to react-native, I don't know.

I want to post information in a different Componen.

Mapview.js (locID, tourInfo,) => ShowInfo.js

You can help me if you study the code. Actually, I have to do something very simple, but I don't know what to do.

I need to send the variables (locID and tourInfo) to the ShowInfo.js Page. To open my location on the map.

Mapview.js

import React from 'react';
import {getDistance, getPreciseDistance} from 'geolib'; // Mesafe Fark hesaplama kütüphanesi
import MapView, {Marker, PROVIDER_GOOGLE, Callout} from 'react-native-maps'; // Harita kullan?m Kütüphansi
import Geolocation from '@react-native-community/geolocation'; // Anroide konum zaman a??m?na u?ramas?n? engellemek i?in kullan?l?r
import {Actions} from 'react-native-router-flux'; // yan menü a?ma ve sayfalar aras?nda ge?i? de kullan?l?r (cihaz?n geri tu?u tri?i var)
import {
  StyleSheet, // Stil Sayfas?
  Image,
  View,
  Dimensions, // Ekran Pencere Boyurlar? anl?k ?eker App dizayn? ona g?re yapar
  TouchableOpacity,
  Text,
} from 'react-native';
const {width, height} = Dimensions.get('window');
import LinearGradient from 'react-native-linear-gradient'; // Düz do?rular yada levhalar yapmak i?in kullan?l?r
import MapViewDirections from 'react-native-maps-directions'; // ?ki mesafe aras?nda rota olu?turan kod
import ImagePicker from 'react-native-image-picker'; // Kamera kulanma ve cihazdan app resim video yükleme kütüphanesi

import * as firebase from 'firebase'; // firebase kütüphanesi importedildi

let locationRef = db.ref('/Location');

import {db} from '../../components/dbConfig/config';
import {requestAuthorization} from 'react-native-geolocation-service';

if (!firebase.apps.length) {
  firebase.initializeApp(db);
}
const rootRef = firebase.database().ref();

export default class Mapview extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      latitude: 0,
      longitude: 0,
      error: null,
      coords: [],
      places: null,
      selectedLat: '',
      selectedLang: '',
      distance: '',
    };
  }
  getLocation = () => {
    Geolocation.getCurrentPosition(position => {
      this.setState({latitude: position.coords.latitude});
      this.setState({longitude: position.coords.longitude});
    });
  };
  setLatLang = (lat, lng) => {
    this.setState({selectedLat: lat});
    this.setState({selectedLang: lng});
  };

  showCoords() {
    const arrayMarkers = [];
    var coordsLatLang = [];
    var allCoords = [];
    var selectedCoordLat = [];
    var selectedCoordLang = [];
    var dis = [];

    Geolocation.getCurrentPosition(position => {
      var userLat = position.coords.latitude;
      var userLang = position.coords.longitude;

      for (let index = 0; index < this.props.locCoord.length; index++) {
        coordsLatLang = this.props.locCoord[index].split(',');
        allCoords.push(this.props.locCoord[index].split(','));
        selectedCoordLat.push(allCoords[index][0]);
        selectedCoordLang.push(allCoords[index][1]);
        dis.push(
          getDistance(
            // Mesafe Hesaplama fonciyonu 2 boyutlu
            {latitude: userLat, longitude: userLang},
            {
              latitude: selectedCoordLat[index],
              longitude: selectedCoordLang[index],
            },
          ),
        );

        var lat = coordsLatLang[0];
        var lng = coordsLatLang[1];

        arrayMarkers.push(
          <Marker
            pinColor={'#24012f'}
            coordinate={{
              latitude: Number(lat),
              longitude: Number(lng),
            }}>
            <Callout
              tooltip
              style={{position: 'relative'}}
              onPress={() => {
                this.setLatLang(
                  selectedCoordLat[index],
                  selectedCoordLang[index],
                );
   

                **if ((dis[index] / 1000).toFixed(2) < 0.5) { ----------------------------
                  Actions.ShowInfo({
                    locationID: this.props.locationID,
                    userName: this.props.userName,
                    rating: this.props.rating,
                    locID: this.props.locID,
                  });
                }**----------------------------------------------------------
              }}>
              <LinearGradient
                start={{x: 0, y: 0}}
                end={{x: 1, y: 0}}
                style={{borderRadius: 20}}
                colors={['#531c5c', '#4b5cab']}>
                <View
                  style={{
                    flexDirection: 'column',
                    alignContent: 'center',
                    alignItems: 'center',
                    flex: 1,
                    padding: 15,
                  }}>
                  <Text
                    style={{color: 'white', fontWeight: 'bold', fontSize: 20}}>
                    {this.props.locNames[index]}
                  </Text>
                  <Text style={{marginTop: 5, color: 'white'}}>
                    Puan?:{this.props.TourLocRating[index].toFixed(2)}
                  </Text>
                  <Text style={{color: 'white'}}>
                    Mesafe:{(dis[index] / 1000).toFixed(2)}KM
                  </Text>
                  <Text style={{marginTop: 5, color: 'white', marginBottom: 5}}>
                    Rota Olu?turmak ??in T?klay?n!
                  </Text>
                </View>
              </LinearGradient>
            </Callout>
          </Marker>,
        );
      }
    });

    this.setState({places: arrayMarkers});
  }

  openCam() {
    // kamera Ba?alama kodu
    ImagePicker.launchCamera(response => {
      // Kameray? ba?lat?r
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      } else {
        const source = {uri: response.uri};

        // You can also display the image using data:  // Verileri kullanarak da g?rüntüyü g?rüntüleyebilirsiniz:
        // const source = { uri: 'data:image/jpeg;base64,' + response.data };

        this.setState({
          avatarSource: source,
        });
      }
    });
  }

  componentWillMount() {
    this.showCoords();
  }

  componentDidMount() {
    this.getLocation();
  }

  render() {
    console.log(this.props.images);
    return (
      <View style={{flex: 1}}>
        <View
          style={{
            backgroundColor: 'white',
            alignItems: 'center',
            width: width,
            height: height * 0.08,
            fontWeight: 'bold',
            flexDirection: 'row',
            justifyContent: 'flex-start',
          }}>
          <TouchableOpacity
            onPress={() => {
              this.props.navigation.goBack();
            }}>
            <Image
              style={{
                width: width * 0.05,
                height: height * 0.03,
                marginTop: 15,
                marginBottom: 10,
                marginLeft: 5,
              }}
              source={require('../../img/back.png')}
            />
          </TouchableOpacity>
          <Image
            resizeMode="contain"
            style={{marginLeft: width * 0.17}}
            source={require('../../img/headerText.png')}
          />
        </View>
        <View style={[styles.lineFooterStyle]} />
        <MapView
          provider={PROVIDER_GOOGLE}
          region={{
            latitude: this.state.latitude,
            longitude: this.state.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}
          showsUserLocation={true}
          style={{flex: 1}}>
          {this.state.places}

          <MapViewDirections // Rota Olu?turmak
            precision={'high'}
            origin={{
              latitude: this.state.latitude,
              longitude: this.state.longitude,
            }} // Mevcut Konum
            destination={{
              latitude: this.state.selectedLat,
              longitude: this.state.selectedLang,
            }} // Hedef Konum
            apikey={'AIzaSyAYGO8DoGtW-v8lEdDbtagGNp5ogtAA8ok'}
            strokeWidth={6}
            strokeColor="#531959"
          />
        </MapView>
        <View>
          <TouchableOpacity
            style={{
              width: width * 0.2,
              height: width * 0.2,
              marginTop: -height * 0.17,
              marginLeft: width * 0.4,
            }}
            onPress={() => this.openCam()}>
            <Image
              style={{
                width: width * 0.2,
                height: width * 0.2,
                marginTop: 15,
                borderRadius: 25,
              }}
              source={require('../../img/ARLogo.png')}
            />
          </TouchableOpacity>
        </View>

        <View style={styles.lineFooterStyle} />
        <View style={styles.footerStyle}>
          <TouchableOpacity
            style={styles.styleInBottombar}
            onPress={() => this.props.navigation.navigate('Mainpage')}>
            <Image
              style={styles.navItemHomeStyle}
              source={require('../../img/Home.png')}
            />
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.styleInBottombar}
            onPress={() => this.props.navigation.navigate('Discover')}>
            <Image
              style={styles.navItemBookmarkStyle}
              source={require('../../img/Bookmark_2.png')}
            />
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.styleInBottombar}
            onPress={() => this.props.navigation.navigate('MyProfile')}>
            <Image
              style={styles.navItemProfileStyle}
              source={require('../../img/Profile.png')}
            />
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

ShowInfo.js

import React from 'react';
import {Actions} from 'react-native-router-flux';
import {
  StyleSheet,
  Text,
  ScrollView,
  Image,
  View,
  Dimensions,
  TouchableOpacity,
  TextInput,
} from 'react-native';

import {AirbnbRating, Rating} from 'react-native-ratings'; // puanlama kütüphanesi Y?ld?z verme
import LinearGradient from 'react-native-linear-gradient'; // düz lehva cigi olu?urmak
import * as firebase from 'firebase'; // firebase kütüphanesi importedildi
import {SliderBox} from 'react-native-image-slider-box'; // resim g?sterme slider yapama kütüphanesi
const {width, height} = Dimensions.get('window'); // Ekran
import Comment from '../HorizontalSlider/Comment'; // yatay kayd?ma yapabilmek i?in kullan?l?r.
let userRef = db.ref('/Users');
let commentsRef = db.ref('/LocationComments');
let locationRef = db.ref('/Location');
import {db} from '../../components/dbConfig/config';
if (!firebase.apps.length) {
  firebase.initializeApp(db);
}

const rootRef = firebase.database().ref();
const loccomme

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are displaying ShowInfo inside MapView, then you can pass that data as props like so:

<ShowInfo data={locID, tourInfo} />

Then in ShowInfo, get the data from props like so:

const locID = this.props.data.locID
const tourInfo = this.props.data.tourInfo

This might be your best bet as I see you're not using React Navigation, so I'm guessing one component will be rendered in the other.

Also, piece of advice, try to be consistent with how you use styling. Either keep all your styles inline or create a style object for all styles. It doesn't really make any difference performance-wise but it does make your code much easier to read.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...