React-native 在页面之间发送信息?

您好,我想将 Mapview.js 重定向到 ShowInfo.js 页面。我想要 重定向时发送 ** locInfo ** 信息。 locInfo 是一个 ShowInfo 中定义的变量。我怎样才能在 Mapview.js 中做到这一点。

在 Mapview.js 中编写此代码时出现错误。

actions.ShowInfo({locationID: this.props.locID })

我的目的;从 Mapview.js 到 ShowInfo 的位置信息、图片描述等。发送。

Mapview.js

import React from 'react';
//import {View,Text} from 'react-native';
import { getDistance,getPreciseDistance } from 'geolib';
import MapView,{ Marker,PROVIDER_GOOGLE,Callout } from 'react-native-maps';
import Geolocation from '@react-native-community/geolocation';
import {
  StyleSheet,Image,View,Dimensions,TouchableOpacity,Text,} from 'react-native';
const { width,height } = Dimensions.get('window');
import LinearGradient from 'react-native-linear-gradient';
import MapViewDirections from 'react-native-maps-directions';
import ImagePicker from 'react-native-image-picker';
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(
          { 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])}>
              <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() {
    ImagePicker.launchCamera((response) => {
      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:
        // 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',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
            precision={"high"}
            origin={{ latitude: this.state.latitude,longitude: this.state.longitude }}
            destination={{ latitude: this.state.selectedLat,longitude: this.state.selectedLang }}
            apikey={'s-v8lEdDbtagGsssssasaNp5ogtAA8ok'}
            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,borderRadius: 25 }}
              source={require('../../img/ARLogo.png')}
            />
          </TouchableOpacity>
      
        </View>
      </View>
    );
  }
}

ShowInfo.js

import React from 'react';
import { actions } from 'react-native-router-flux';
import {
    StyleSheet,ScrollView,TextInput
} from 'react-native';

import { AirbnbRating,Rating } from 'react-native-ratings';
import LinearGradient from 'react-native-linear-gradient';
import * as firebase from 'firebase';
import { SliderBox } from "react-native-image-slider-box";
const { width,height } = Dimensions.get('window');
import Comment from '../HorizontalSlider/Comment';
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 loccommentRef = rootRef.child('LocationComments');

let addItem = (comment,locationID,username,rating,comments,locID) => {
    loccommentRef.push({
        comment: comment,LocationID: locationID,username: username,users: [],rating: rating
    });
    var count = 0;
    var newRating = 0;
    for (let index = 0; index < comments.length; index++) {
        if (locID == comments[index].LocationID) {
            count++;
            newRating += comments[index].rating
        }
    }
    var generalNewRating = (newRating + rating - 1) / count
    locationRef.child(locID).update({ 'Rating': generalNewRating })
};

export default class ShowInfo extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            locInfo: [],comments: [],comment: '',username: '',userEmail: '',rating: '',};
    }

    ratingCompleted = (rating) => {
        this.setState({ rating: rating })
    }

    getUserData() {
        userRef.on('value',snapshot => {
            let data = snapshot.val();
            let users = Object.values(data);
            this.setState({ users: users });
        });
    }

    getcomments() {
        commentsref.on('value',snapshot => {
            let data = snapshot.val();
            let comments = Object.values(data);
            this.setState({ comments: comments });
        });
    }

    getLocationData() {
        locationRef.on('value',snapshot => {
            let data = snapshot.val();
            let locInfo = Object.values(data);
            this.setState({ locInfo: locInfo });
        });
    }

    getusername = () => {
        for (let index = 0; index < this.state.users.length; index++) {
            if (this.props.userEmail == this.state.users[index].email) {
                return this.state.users[index].username;
            }
        }
    }
    updateRating = () => {
        var count = 0;
        for (let index = 0; index < this.state.comments.length; index++) {
            if (this.props.locID == this.state.comments[index].LocationID) {
                count++;
            }
        }
        locationRef.child(this.props.locID).update({ 'Rating': (this.state.locInfo[this.props.locID].Rating + this.state.rating) / count })
    }


    componentWillMount() {
        this.getLocationData()
        this.getUserData()
        this.getcomments()
    }
    inRender(images,commentContext,locCoord,locNames) {

        console.log(this.state.locInfo[2].Rating,"---")
        if (this.getusername() != null) {
            this.setState({ username: this.getusername() })
        }
        for (let index = 0; index < this.state.locInfo.length; index++) {
            if (this.props.locID == this.state.locInfo[index].ID) {
                images = this.state.locInfo[index].Image.split(',')
                locCoord.push(this.state.locInfo[index].Coordinate)
                console.log(locCoord)
                locNames.push(this.state.locInfo[index].Name)
            }
        }
        for (let index = 0; index < this.state.comments.length; index++) {
            if (this.props.locID == this.state.comments[index].LocationID) {
                comments.push(this.state.comments[index])
            }
        }
        for (let index = 0; index < comments.length; index++) {
            if (comments[index].username != "") {
                commentContext.push(
                    <Comment
                        username={comments[index].username}
                        comment={comments[index].comment}
                        rating={comments[index].rating}
                    />
                )
            }
        }
        return images;
    }
    render() {
        var locNames = [];
        var images = [];
        var comments = [];
        var commentContext = [];
        var locCoord = []
        var retImages = this.inRender(images,locNames);
        var TourLocRating = [];
        TourLocRating.push(this.props.rating)
        return (
            <View style={{ flex: 1,backgroundColor: 'white' }}>
                <View style={{
                    backgroundColor: 'white',}}>
                    <TouchableOpacity onPress={() => { this.props.navigation.goBack() }}>
                        <Image
                            style={{ width: width * 0.05,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]} />
                <ScrollView>
                    <SliderBox
                        style={{ height: height * 0.4,marginLeft: 5,marginRight: 5 }}
                        imageLoadingColor="white"
                        dotColor="white"
                        inactiveDotColor="#90A4AE"
                        autoplay
                        disableonPress
                        circleLoop
                        images={retImages}
                    //currentImageEmitter={index => locName=imgSliderHolder[index].Name} //Resim üzerinde lokasyonun adını gösterebilirsin. Resim geldiğinde gerçekleşen func. 
                    //onCurrentImagepressed={index => actions.ShowInfo({ locImage: images[index],tourName: imgSliderHolder[index].Name,info: imgSliderHolder[index].Info })}
                    />
                    <View style={{ marginLeft: 15 }}>
                        <View style={{ flexDirection: 'row' }}>
                            <View style={{ flexDirection: 'column' }}>
                                <View style={{ marginTop: 30 }}>
                                    <Text style={{ color: '#171c69',fontSize: 15,marginLeft: height * 0.01 }}>{this.props.tourName}</Text>
                                    <LinearGradient style={styles.gradientLinestyle} start={{ x: 0,y: 1 }} end={{ x: 1,y: 1 }} colors={['#3E276F','#F9F7F6']}></LinearGradient>
                                </View>
                                <TouchableOpacity style={styles.BtnStyleLogin} onPress={() => actions.LocMapview({ locCoord: locCoord,locNames,kind: "location",TourLocRating })}>
                                    <Text style={{ color: 'white' }}>
                                        Başla
                            </Text>
                                </TouchableOpacity>
                                <View style={{ flexDirection: 'row' }}>
                                    <Rating
                                        readonly={true}
                                        startingValue={this.props.rating}
                                        style={{ paddingVertical: 10 }}
                                        imageSize={20}
                                    />
                                    <Text style={{ marginLeft: width * 0.02,marginBottom: height * 0.015,marginTop: height * 0.012,fontWeight: 'bold' }}>Puanı:{this.props.rating.toFixed(2)}</Text>
                                </View>
                            </View>
                            <TouchableOpacity onPress={() => this.playSound()}>
                                <Image style={{ width: 40,height: 40,marginTop: height * 0.1,}}
                                    source={require('../../img/sound_button.png')}
                                />
                            </TouchableOpacity>
                        </View>
                        <View style={{ flexDirection: 'row',marginBottom: 15,justifyContent: 'space-between' }}>
                            <TouchableOpacity onPress={() => { this.refs._scrollView.scrollTo(); }}>
                                <Text style={{ color: '#171c69',marginLeft: height * 0.025 }}>Hakkında</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => { this.refs._scrollView.scrollTo({ x: width,y: 0 }); }}>
                                <Text style={{ color: '#171c69',marginRight: 15 }}>Değerlendir</Text>
                            </TouchableOpacity>
                        </View>
                        <LinearGradient style={styles.gradientLinestyle} start={{ x: 0,'#F9F7F6']}></LinearGradient>
                    </View>



                    <ScrollView
                        ref='_scrollView'
                        horizontal={true}
                        pagingEnabled={true}
                    >
                        <View style={{
                            flex: 1,}}>
                            <Text style={{ padding: 15,textAlign: 'justify' }}>{this.props.info}</Text>
                        </View>
                        <View
                            style={{
                                flex: 1,padding: 15
                            }}>
                            <TextInput
                                style={{ height: 150,borderColor: 'gray',borderWidth: 0.5,borderRadius: 25 }}
                                multiline={true}
                                onChangeText={comment => this.setState({ comment })}
                            />
                            <View style={{ flexDirection: 'row',justifyContent: 'space-between' }}>
                                <View style={{ marginTop: 20 }}>
                                    <AirbnbRating
                                        count={5}
                                        showRating={false}
                                        onFinishRating={this.ratingCompleted}
                                        defaultRating={0}
                                        size={30}
                                        fractions={2}
                                    />
                                </View>
                                <TouchableOpacity style={{
                                    width: width * 0.3,height: height * 0.06,borderRadius: 15,justifyContent: 'center',backgroundColor: '#1a345c',}} onPress={() => addItem(this.state.comment,this.props.locID,this.state.username,this.state.rating,this.state.comments,this.props.locID)}>
                                    <Text style={{ color: 'white' }}>
                                        Değerlendir
                            </Text>
                                </TouchableOpacity>
                            </View>
                            <Text style={{ color: '#171c69',fontSize: 25,marginTop: 15 }}>Yorumlar</Text>
                            {commentContext}
                        </View>

                    </ScrollView>

                </ScrollView>
                <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>
        );
    }
}
kevin1985108 回答:React-native 在页面之间发送信息?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/1141786.html

大家都在问