Я новичок в том, чтобы реагировать на натив, но последние несколько часов я безрезультатно изучал, как перенаправить на новые действия с помощью кнопок. В моем текущем решении я использую реагирующую навигацию из нескольких файлов, а App.js создает StackNavigator для остальных страниц. Однако всякий раз, когда я нажимаю кнопку на Initial.js, ничего не происходит.
Я следил за руководством Дэмиена Мэнсона по Нарушение инварианта: для этого навигатора отсутствует навигационная опора., но кнопка по-прежнему не работает. Я пытался сослаться на приложение перед вызовом моей кнопки, но всякий раз, когда я пытаюсь запустить его на эмуляторе, он не показывает мне журнал ошибок и никогда не загружается. Он остается на «Загрузка пакета JavaScript: 100%» в течение нескольких минут, пока сам эмулятор не выйдет из строя.
Вот мой App.js
import Initial from './components/Initial'
import Statistics from './components/Statistics'
const RootStack = createStackNavigator({
Default: {
screen: Initial
},
Stats: {
screen: Statistics
}
});
const App = createAppContainer(RootStack);
export default App;
Вот мой Initial.js
import { StyleSheet, ImageBackground, Image, View, Text, Button } from 'react-native';
import { Font } from 'expo';
import App from '../App';
import {withNavigation} from 'react-navigation';
import Statistics from './Statistics';
export default class Initial extends React.Component {
static navigationOptions = {header: null}
componentDidMount() {
Font.loadAsync({'pt': require('../assets/fonts/pt.ttf')});
Font.loadAsync({'Karla': require('../assets/fonts/Karla-Regular.ttf')});
Font.loadAsync({'Space-Mono': require('../assets/fonts/SpaceMono-Regular.ttf')});
}
state = { fontLoaded: false};
async componentDidMount() {
await Font.loadAsync({'pt': require('../assets/fonts/pt.ttf'),});
await Font.loadAsync({'Karla': require('../assets/fonts/Karla-Regular.ttf'),});
await Font.loadAsync({'Space-Mono': require('../assets/fonts/SpaceMono-Regular.ttf'),});
this.setState({fontLoaded: true});
}
render() {
return (
<ImageBackground
source = {require('../assets/blue-bin.jpg')}
style = {styles.container}>
<View style = {styles.parentView}>
{this.state.fontLoaded ? (<Text style = {styles.logoText}>!arbitrary</Text>) : null}
<Image source = {require('../assets/sadparrot.gif')} style = {styles.logo}/>
<Text style = {styles.textBox}>With its easily navigatible interface, the Chicago-based app, !arbitrary, aims to educate the masses about recyclable items, while emphasizing the importance of being sustainable.</Text>
<View style = {styles.redirect}>
<Button
title = "Start"
onPress = {() => this.props.navigation.navigate('Statistics')}
/>
</View>
</View>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
width: '100%',
height: '100%',
},
parentView: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'rgba(5,9,12, 0.6)',
justifyContent: 'center',
alignItems: 'center'
},
logoText: {
color: '#fff',
fontSize: 36,
fontFamily: 'pt'
},
textBox: {
width: 200,
height: 175,
fontFamily: 'sans-serif',
fontSize: 14,
color: '#fff',
borderColor: '#fff',
borderWidth: 2,
justifyContent: 'center',
marginTop: 50,
padding: 20
},
logo: {
width: 200,
height: 200
},
redirect: {
width: 80,
height: 30,
marginTop: 30
},
statistics: {
flex: 1,
width: '100%',
height: '100%',
backgroundColor: '#1B384F'
},
bigText: {
color: '#fff',
fontSize: 20,
fontFamily: 'Space-Mono'
}
});
Вот моя статистика.js
import { StyleSheet, ImageBackground, Image, View, Text, Button } from 'react-native';
import { Font } from 'expo';
import {withNavigation} from 'react-navigation';
class Statistics extends React.Component {
render() {
return(
<Text>Avail!</Text>
);
}
}
export default withNavigation(Statistics);
ПРИМЕЧАНИЕ. Я пропустил таблицу стилей в Initial.js для краткости.
Я была такая же проблема. Я исправил это с помощью withNavigation
В классе Статистика,
1-й, Импорт withNavigation
.
import { withNavigation } from 'react-navigation';
Затем экспортируйте класс Статистика, как показано ниже.
export default withNavigation(Statistics)
Можете ли вы также добавить эти два утверждения в класс Initial
?
Просто добавил их, но теперь экран по умолчанию — Statistics.js. Разве мне не нужно было бы вместо этого делать export default Initial extends React.Component
?
Да, пожалуйста. Измените его обратно на export default Initial extends React.Component
. Это странно. Я исправил ту же проблему с помощью вышеуказанного метода (решения).
Require cycle: App.js -> components\Initial.js -> App.js
Это просто предупреждение. Я прав? Вы пробовали отклонить его?
Да, я изменил его обратно, и Initial.js теперь является экраном по умолчанию, однако кнопка по-прежнему не работает.
@ Летта, нет необходимости использовать withNavigation
, имя вашего маршрута Stats
, но вы хотите перейти к Statistics
, который существует в RootStack
.
Вам нужно перейти к своему отображаемому имени, которое Stats
.
<Button
title = "Start"
onPress = {() => this.props.navigation.navigate('Stats')}/>
поскольку вы шли по несуществующему маршруту, ваши маршруты называются Stats
и Default
.
Попробуй это
const RootStack = createStackNavigator({
Default: {
screen: Initial
},
Stats: {
screen: props => <Statistics {...props} />
}
});
Я добавил свой Statistics.js в свой первоначальный вопрос с вашим предложением. Приложение теперь вообще не запускается, а вместо этого отображает ошибку (или предупреждение?)
Require cycle: App.js -> components\Initial.js -> App.js