问题
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 loccommentRef = rootRef.child('LocationComments');
let addItem = (comment, locationID, userName, rating, comments, locID) => {
// kullanıcı konuma yorum yapma işlemi
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: '',
users: [],
};
}
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, comments, 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(',');
console.log(
' :LocID değeri********* ',
this.state.locInfo[index],
' --00ss- ',
index,
);
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,
commentContext,
comments,
locCoord,
locNames,
);
var TourLocRating = [];
TourLocRating.push(this.props.rating);
return (
<View style={{flex: 1, backgroundColor: 'white'}}>
<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]} />
<ScrollView>
<SliderBox
style={{height: height * 0.4, marginLeft: 5, marginRight: 5}}
imageLoadingColor="white"
dotColor="white"
inactiveDotColor="#90A4AE"
autoplay
disableOnPress
circleLoop
images={retImages}
// Dizi olarak tutulur resimin ya yolu yada linki bulunur
//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',
fontWeight: 'bold',
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']}
/>
</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ı:
</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,
marginTop: 15,
justifyContent: 'space-between',
}}>
<TouchableOpacity
onPress={() => {
this.refs._scrollView.scrollTo();
}}>
<Text
style={{
color: '#171c69',
fontWeight: 'bold',
fontSize: 15,
marginLeft: height * 0.025,
}}>
Hakkında
</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.refs._scrollView.scrollTo({x: width, y: 0});
}}>
<Text
style={{
color: '#171c69',
fontWeight: 'bold',
fontSize: 15,
marginRight: 15,
}}>
Değerlendir
</Text>
</TouchableOpacity>
</View>
<LinearGradient
style={styles.gradientLineStyle}
start={{x: 0, y: 1}}
end={{x: 1, y: 1}}
colors={['#3E276F', '#F9F7F6']}
/>
</View>
<ScrollView ref="_scrollView" horizontal={true} pagingEnabled={true}>
<View
style={{
flex: 1,
width: width,
}}>
<Text style={{padding: 15, textAlign: 'justify'}}>
{this.props.info}
</Text>
</View>
<View
style={{
flex: 1,
width: width,
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,
marginTop: 15,
marginBottom: 15,
borderRadius: 15,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#1a345c',
flexDirection: 'row',
}}
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',
fontWeight: 'bold',
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>
);
}
}
回答1:
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.
回答2:
You can use
this.props.navigation.navigate('Example', { locID: "", tourInfo: "", userName: "", userEmail: "" });
in Mapview.js when you navigate to the other page, then in ShowInfo.js you get them like this:
var locID = this.props.navigation.getParam('locID', "");
var tourInfo= this.props.navigation.getParam('tourInfo', "");
var userName= this.props.navigation.getParam('userName', "");
var userEmail= this.props.navigation.getParam('userEmail', "");
来源:https://stackoverflow.com/questions/65648574/switching-between-pages-in-react-native-also-return-information