【发布时间】:2021-12-03 08:17:04
【问题描述】:
我正在尝试使用外部按钮组件来使用 React Navigation,以简化样式设置,但是当我尝试通过导航时,它给了我TypeError: undefined is not an object (evaluating '_this.props.navigation') 错误。如果我在主屏幕上创建按钮,它可以正常工作,但这会使我的 HomeScreen 的样式表变得混乱,这意味着当我在其他地方使用该按钮时必须重复代码。
我在我的 App.js 中设置了堆栈导航,当我不尝试将导航作为道具传递时,它再次工作正常。
这里是 HomeScreen.js
import React from "react";
import {
ScrollView,
StyleSheet,
Text,
View,
AsyncStorage,
} from 'react-native';
import Heading from '../heading';
import Input from '../Input';
import Button from "../Button";
export const Home = ({navigation}) => (
<View style={styles.container}>
<ScrollView style={styles.content}>
<Heading />
</ScrollView>
<Button/>
</View>
)
这是我的 Button.js
/* eslint-disable prettier/prettier */
import React from 'react';
import {
StyleSheet,
Text,
View,
TouchableHighlight
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
function Button(){
const navigation = useNavigation()
return(
<View style={styles.buttonContainer}>
<TouchableHighlight
underlayColor='rgba(175, 47, 47, .75)'
activeOpacity={1.0}
style={styles.button}
onPress={() => {
navigation.navigate("New Medication");
}}>
<Text style={styles.submit}>
+
</Text>
</TouchableHighlight>
</View>
)
}
据我了解,这应该可以正常工作,那为什么说它是作为未定义传递的?
更新:多亏了一些建议,我现在将它带到了不会出错的地方,只是什么都不做。
这是我的 App.js,带有我的导航
const Stack = createStackNavigator();
function MyStack() {
return (
<Stack.Navigator
screenOptions={{
headerShown: false
}}>
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="NewMedication" component={newMedScreen} />
</Stack.Navigator>
);
}
class App extends Component{
render(){
return(
<NavigationContainer>
<MyStack />
</NavigationContainer>
);
}
}
export default App;
【问题讨论】:
-
因为功能组件中的
this与类中的不一样 -
@Horst 这确实有帮助,因为没有错误,谢谢。现在按钮什么都不做,但更接近了。
-
顺便说一句,您不需要向下传递导航。有一个钩子
useNavigation。 -
函数组件是无实例的,
this只是未定义。this.props不起作用,您可以将解构后的navigation属性传递给按钮。 -
@Horst 好的,我设置了 useNavigation,传递了解构的道具和所有内容,但现在我的按钮在单击时什么也不做。
标签: javascript reactjs react-native react-navigation