反应本机按钮按什么也没发生,也改变文本不起作用



我是React Native的新手。我有一个包含两个字段的登录表单。我想在将用户发送到仪表板之前对用户进行身份验证.js。无论我尝试什么,按钮都没有做任何事情(绝对什么都没有发生,没有错误(。我将代码保存在登录中.js以显示我尝试做的所有事情,即

  1. 路由到仪表板.js
  2. 尝试通过在按下按钮时调用句柄提交按钮函数来执行某些操作。
  3. 弹出警报。

我用了两个按钮。一个来自 react-native-paper,一个来自 react-native。 我在下面提供我的应用程序代码.js和登录.js。请有人帮忙吗?

法典

App.js
import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import DashBoard from "./mainmenu/DashBoard";
import Login from "./mainmenu/Login";

const Stack = createStackNavigator();

export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="DashBoard" component={DashBoard} />
</Stack.Navigator>
</NavigationContainer>
);
}


Login.js
import React, { useState } from "react";
import { Title, TextInput} from "react-native-paper";
import { View, Alert,Button } from "react-native";
export default function Login() {
const [mobile, setMobile] = useState("123456789");
const [password, setPassword] = useState("123");

function handleSubmitPress() {
console.log({ mobile, password });
}

return (
<View
style={{
backgroundColor: "skyblue",
alignItems: "center",
justifyContent: "center",
}}
>
<TextInput
label="Your mobile number "
value={mobile}
onChangeText={(text) => setMobile(text)}
/>
<TextInput
label="Type Password  "
value={password}
onChangeText={(text) => setPassword(text)}
/>

<Button
icon="camera"
type="submit"
mode="contained"
//onPress={() => props.navigation.navigate("DashBoard")}
onPress={()=>Alert.alert('Navigate pressed')}
>
Navigate
</Button>

<Button
title="Print"
onPress={() => Alert.alert('Simple Button pressed')}
// onPress={handleSubmitPress()}
/>
</View>
);
}

将登录组件更改为此组件。

...
const Login = ({navigation}) => {
const [mobile, setMobile] = useState('123456789');
const [password, setPassword] = useState('123');
function handleSubmitPress() {
console.log({mobile, password});
}
return (
<View
style={{
backgroundColor: 'skyblue',
alignItems: 'center',
justifyContent: 'center',
}}>
<TextInput
label="Your mobile number "
value={mobile}
onChangeText={text => setMobile(text)}
/>
<TextInput
label="Type Password  "
value={password}
onChangeText={text => setPassword(text)}
/>
<Button
title="title"
icon="camera"
type="submit"
mode="contained"
onPress={() => navigation.navigate('DashBoard')}>
Navigate
</Button>
<Button title="Print" onPress={() => handleSubmitPress()} />
</View>
);
};
export default App;

有几个问题。

我使用了默认的 React Native 按钮。所以我在其中一个按钮中添加了一个标题道具,因为这是必需的。我给它的值"title",但将其更改为您想要的值或使用 React Native Paper 按钮。

主要问题是你如何在按钮onPress中调用handleSubmitPress

你的onChangeText很好,你只是看不到结果,因为没有调用handleSubmitPress

我还使用了解构,因此您可以直接访问导航道具。您也可以执行const Long = (props) => {...}并使用props.navigation,但无论哪种方式,您都需要传入一些东西,否则导航将不起作用。

最新更新