完成新手以對原生和編程作出反應。反應本機:組件之間的溝通
跟隨TutorialPoint中的教程並試圖通過道具將數據從一個組件傳遞到另一個組件。我不能爲了我的生活找出它爲什麼不工作,並希望任何人都可以指出一個初學者在正確的方向。
這是鏈接到tutorialspoint我是以下幾點:
https://www.tutorialspoint.com/react_native/react_native_geolocation.htm
唯一的區別是,我的index.android.js有一個滾動式標籤視圖所以「演示組件」是一個標籤。
GeolocationExample和HomeContainer都位於名爲「app」的文件夾中。我的問題是,HomeContainer似乎沒有通過道具將變量initialposition和lastposition傳遞給GeolocationExample。我試圖運行它時看到的一個空白屏幕是初始位置和LastPosition:
哦,我已經更改了Android清單,以包含訪問精確位置的權限,所以這不是問題。
請提前謝謝!
這是index.android.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
ScrollView,
Navigator,
View
} from 'react-native';
import ScrollableTabView, { ScrollableTabBar, } from 'react-native-scrollable-tab-view';
import GeolocationExample from './app/GeolocationExample';
export default class test extends Component {
render() {
return (
<ScrollableTabView
tabBarPosition='bottom'
initialPage={0}
renderTabBar={() => <ScrollableTabBar/>}
tabBarUnderlineColor='#123456'
tabBarBackgroundColor='#FFFFFF'
tabBarActiveTextColor='#4682b4'
tabBarInactiveTextColor='#696969'
tabBarTextStyle={{fontSize: 14,fontWeight: "bold"}}>
<Welcome tabLabel='Welcome' />
<GeolocationExample tabLabel='LocationTest'/>
</ScrollableTabView>
);
}
}
AppRegistry.registerComponent('test',() => test);
這是GeolocationExample.js
import React, { Component } from 'react';
import {
Text,
View,
StyleSheet
} from 'react-native';
export default GeolocationExample = (props) => {
return (
<View style = {styles.container}>
<Text>
<Text style = {styles.boldText}>
Initial position:
</Text>
{props.initialPosition}
</Text>
<Text>
<Text style = {styles.boldText}>
Current position:
</Text>
{props.lastPosition}
</Text>
</View>
);
}
const styles = StyleSheet.create ({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginTop: 70
},
boldText: {
flex: 1,
fontWeight: 'bold'
}
});
最後一點是HomeContainer
import React, { Component } from 'react'
import GeolocationExample from './GeolocationExample'
export default class HomeContainer extends Component {
constructor() {
super();
this.state = {
initialPosition: 'unknown',
lastPosition: 'unknown'
}
}
watchID = (null: ?number);
componentDidMount =() => {
navigator.geolocation.getCurrentPosition(
(position) => {
var initialPosition = JSON.stringify(position);
this.setState({initialPosition});
},
(error) => alert(error.message),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
this.watchID = navigator.geolocation.watchPosition((position) => {
var lastPosition = JSON.stringify(position);
this.setState({lastPosition});
});
}
componentWillUnmount =() => {
navigator.geolocation.clearWatch(this.watchID);
}
render() {
return (
<GeolocationExample
initialPosition = {this.state.initialPosition}
lastPosition = {this.state.lastPosition}
/>
);
}
}