素胚勾勒不出你
2022-06-09 19:41:47
我是 JS/React-native 的新手,我對如何正確管理地圖的初始狀態有點困惑。我有以下組件:import React from 'react';import { StyleSheet, Text, View, Dimensions} from 'react-native';import Colors from '../constants/Colors'import MapView from 'react-native-maps'const { width, height } = Dimensions.get('window');const ASPECT_RATIO = width / height;const LATITUDE = 53.2274476;const LONGITUDE = -0.5474525;const LATITUDE_DELTA = 0.0922;const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;function myMapsComponent({navigation}) { constructor(props) { super(props); this.state = { isLoading: true, location: null, errorMessage: null, region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, } } return ( <MapView style={{flex: 1}} Initialregion={this.state.region}/> );}const styles = StyleSheet.create({});export default myMapsComponent;此代碼產生錯誤expected ";" (16:21),這是構造函數開始的行。我猜問題實際上是我不能使用構造函數,除非它在類而不是函數中?有人可以在這里指出我正確的方向嗎?
1 回答

斯蒂芬大帝
TA貢獻1827條經驗 獲得超8個贊
你是對的,你不能在函數組件中使用構造函數。
你能做的就是選擇一個或另一個。一個類組件看起來像這樣:
class MyMapsComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
...
}
}
render() {
return (
<MapView style={{flex: 1}} Initialregion={this.state.region}/>
);
}
}
還有一個像這樣的功能組件:
function myMapsComponent({navigation}) {
const [isLoading, setLoading] = useState(false);
const [region, setRegion] = useState({longitude: LONGITUDE, ...});
...
return (
<MapView style={{flex: 1}} Initialregion={region}/>
);
}
您可以在此處了解組件(函數或類),并在此處了解關于和其他useState鉤子
添加回答
舉報
0/150
提交
取消