我正在使用以下代码在React Native中显示一个带有按钮的“主页”......它可以正常工作:
import React, { useState } from 'react';
import { Button, Text, TextInput, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button title="Go to Login" onPress={() => navigation.navigate('Login')} />
</View>
);
}
function LoginScreen({ navigation }) {
//do things to login here
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Login" component={LoginScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
当我尝试修改代码以根据全局变量的值在“主页”页面上显示按钮时,问题出现了,我得到了一个错误。我不确定为什么“HomeScreen”函数无法识别“_secured”变量的值......?
import React, { useState } from 'react';
import { Button, Text, TextInput, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
var _secured = 0;
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
if (_secured === 0) {
<Button title="Go to Login" onPress={() => navigation.navigate('Login')} />
} else {
<Button title="Stuff" onPress={() => navigation.navigate('DoStuff')} />
}
</View>
);
}
function LoginScreen({ navigation }) {
//do things to login here
}
function StuffScreen({ navigation }) {
//do other things here
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="DoStuff" component={StuffScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
任何建议非常感谢,我是新的React本土。我提前感谢你。
不幸的是,我仍然有巨大的困难试图弄清楚这一点,这是令人难以置信的沮丧。我相信我需要定义我的'全局'变量使用'useState'。我的代码为'主页'屏幕如下:
function HomeScreen({ navigation }) {
const [isLogged, setLog] = useState(0);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
(isLogged === 0) ? (<Button title="Go to Login"> onPress={() => navigation.navigate('Login')} </Button>) : (<Button title="Stuff"> onPress={() => navigation.navigate('DoStuff')} </Button>)
}
如前所述,我是React Native开发的新手。无法使用简单的if/else语句来完成这一点是非常令人沮丧的。我提前感谢任何人的一些见解。
1条答案
按热度按时间dwbf0jvd1#
就像普通函数一样,react renderer不能返回多个JSX元素,因此将原始代码封装在一个JSX EmptyView
<></>
中,然后使用JS计算条件,最后返回一个按钮视图。