App.js
const Stack = createNativeStackNavigator();
export default function App() {
return (
<Provider store={store}>
<NavigationContainer>
<Stack.Navigator initialRouteName="Main">
<Stack.Screen options={{headerShown: false}} name="Main" component={MainScreen} />
<Stack.Screen options={{headerShown: false}} name="Report" component={ReportScreen} />
</Stack.Navigator>
</NavigationContainer>
</Provider>
);
}
/screens/ReportScreen.js
import React from 'react';
import {
StyleSheet,
SafeAreaView,
View,
Text,
} from 'react-native';
import ReportReason from '../components/ReportReason';
const ReportScreen = ({route}) => {
const textVal = '';
if (route.param.title.length > 12){
textVal = route.params.title.substring(0,10) + '...';
}
else {
textVal = route.params.title;
}
return(
<SafeAreaView style = {reportStyles.container}>
<View style = {reportStyles.card}>
<Text>Report</Text>
<Text>{textval}</Text>
<ReportReason/>
</View>
</SafeAreaView>
);
};
的一部分/components/ReportMension.js
const ReportMension = ({mension}) => {
return(
TouchableOpacity style={postModalStyles.listButton} onPress={()=>{
console.log(mension)
navigation.navigate('Report', { title: mension.title });
}}>
<Text style={postModalStyles.text}>report</Text>
</TouchableOpacity>
);
}
这是名为Main的屏幕组件。
console.log运行正常。为什么我的组件和导航器不能传递params(props)?使用stacknavigaor时如何传递道具??
首先,在ReportMention中,不能重新分配const
变量。相反,尝试
let textVal = '';
if (route.params.title.length > 12) {
textVal = route.params.title.substring(0,10) + '...';
}
else {
textVal = route.params.title;
}
或
const textVal = route.params.title.length > 12
? route.params.title.substring(0,10) + '...'
: route.params.title;
其次,条件中有一个拼写错误:route.param.title.length
应该是route.params.title.length
。这将引发一个错误,因为您无法访问未定义对象的属性length
。
这两个语法错误应该会阻止快速刷新,因为结果不会编译。如果你修复了这些问题,并在ReportMention中console.logroute
对象,你应该会得到你想要的params。