我是一个新的React Native & 我试图创建分离的Button组件文件(可重用的组件),当我按下按钮时,它将导航到另一个页面(react-navigation)。以下是我的代码。
GlobalButton.js
import React from 'react'
import { StyleSheet, TouchableOpacity, Text} from 'react-native'
import { useNavigation, NavigationContainer } from '@react-navigation/native';
const GlobalButton = (props, {screenName}) => {
const navigation = useNavigation();
return
<TouchableOpacity style={[styles.btn, props.style]} onPress= {() => navigation.navigate(screenName)}>
{props.children}
</TouchableOpacity>
}
const styles = StyleSheet.create({
btn: {
alignItems: 'center',
textAlign: 'center',
borderRadius: 25,
height: 50,
}
})
export default GlobalButton;
登录页面.js
import React from 'react'
import { StyleSheet, Text, View, Image, TextInput, Button} from 'react-native'
import ButtonLogin from '../components/GlobalButton'
// import { useNavigation, NavigationContainer } from '@react-navigation/native';
export default function LoginPage() {
return (
<View style={styles.penampung}>
<Image source= {require('../assets/beetle.png')} style={styles.gambar}/>
<TextInput style={styles.textField} placeholder='username' />
<TextInput style={styles.textField} placeholder='password' secureTextEntry={true} />
<ButtonLogin style={styles.btnStyle} screenName="MainPage"><Text style={styles.text}>LOGIN</Text></ButtonLogin>
</View>
)
}
const styles = StyleSheet.create({
penampung: {
flex: 1,
alignItems: 'center',
backgroundColor: '#00688B',
justifyContent: 'center'
},
gambar: {
height: 100,
width: 100,
},
textField: {
marginTop: 25,
backgroundColor: '#cafafe',
borderRadius: 25,
width: '80%',
height: 50,
paddingLeft: 20
},
btnStyle: {
padding: 10,
position: 'absolute',
bottom: 20,
backgroundColor: "#fc4445",
width: '80%'
},
text:{
fontSize: 20,
fontWeight: 'bold',
color: 'white'
}
})
我期望的是,当我点击登录按钮时,它应该导航到MainPage.js,但它却给出了错误信息->错误,当你点击登录按钮时,你需要指定名称或键,而不是给出错误信息-> 错误。You need to specify name or key when calling navigate with an object as the argument.
请任何人帮助我在这个问题上,谢谢......
你应该像下面这样做,因为screenName是你的道具的一部分。
<TouchableOpacity style={[styles.btn, props.style]} onPress= {() => navigation.navigate(props.screenName)}>