我正在嘗試通過 props.naviagtion.getParam 將資料從一個螢屏獲取到另一個螢屏,但是我收到此錯誤:'TypeError: props.navigation.getParam 不是函式。(在 'props.navigation.getParam('docId')' 中,'props.navigation.getParam' 未定義)'。我已經分享了代碼;如果有人熟悉這個問題,您的幫助將不勝感激!
import { useNavigation } from '@react-navigation/core'
import React from 'react'
import { StyleSheet, Text, TouchableOpacity, View, FlatList, ScrollView, Pressable } from 'react-native'
import { auth } from '../firebase'
import { DOC } from '../Data/dummy-data'
const HomeScreen = props => {
const navigation = useNavigation()
const handleSignOut = () => {
auth
.signOut()
.then(() => {
navigation.replace("Login")
})
.catch(error => alert(error.message))
}
const renderGridItem = (itemData) => {
return (
<TouchableOpacity
style={styles.grid}
onPress={ () => {
navigation.navigate('Doctors',{docId:itemData.item.id})
}}>
<View>
<Text>
{itemData.item.title}
</Text>
</View>
</TouchableOpacity>
)
}
return (
<View style={styles.container}>
<FlatList keyExtractor={(item, index) => item.id}
data={DOC}
renderItem={renderGridItem} />
<Text style={styles.txt}>Email: {auth.currentUser?.email}</Text>
<TouchableOpacity
onPress={handleSignOut}
style={styles.button}
>
<Text style={styles.buttonText}>Sign out</Text>
</TouchableOpacity>
</View>
)
}
HomeScreen.navigationOptions = {
headerTitle: 'All Doctors',
headerStyle: {
backgroundColor: 'red'
},
headerTintColor: 'red'
};
export default HomeScreen
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
backgroundColor: '#0782F9',
width: '60%',
padding: 15,
borderRadius: 10,
alignItems: 'center',
marginTop: 40,
},
buttonText: {
color: 'white',
fontWeight: '700',
fontSize: 16,
},
txt:{
fontSize:20,
color:'black',
alignItems:'flex-start'
},
screen:{
marginTop:10,
width:'30%',
height:2,
borderRadius:10,
backgroundColor:'red',
},
grid:{
flex:1,
margin:15,
height:150
},
})
////////////Doctor.js/////////////
import { StyleSheet, Text, View } from 'react-native'
import React from 'react'
import { DOC } from '../Data/dummy-data'
const Doctors = props => {
const docId = props.navigation.getParam('docId')
const selectedCategory = DOC.find(doc => doc.id === docId)
return (
<View>
<Text>{selectedCategory.title}</Text>
</View>
)
}
export default Doctors
const styles = StyleSheet.create({})
uj5u.com熱心網友回復:
您需要注意兩件事。首先,如果Doctors不是導航器中的螢屏,則route導航框架不會將物件傳遞給它。其次,如果您正在使用react-navigation v5 or higher,那么您可以訪問params via the route object.
由于您導航到Doctors,它應該是導航器中定義的螢屏,因此您可以按如下方式訪問它。
const Doctors = props => {
// destructure
const { docId } = props.route.params
const selectedCategory = DOC.find(doc => doc.id === docId)
return (
<View>
<Text>{selectedCategory.title}</Text>
</View>
)
}
如果您在導航器中有一個不是螢屏的組件,那么您可以使用該useRoute鉤子。
const route = useRoute()
const { docId } = route.params
參考: 的最后一個版本getParams是v4記錄在這里。這已針對此處記錄的更高版本進行了更改。此處記錄了useRoute 掛鉤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/485328.html
標籤:javascript 反应 反应式 反应导航 反应道具
下一篇:無法使用類組件中的道具設定狀態
