我是 react 原生新手。现在我需要在两个屏幕上实现一个功能。当我单击“addActivity”场景中的底部时,它将返回“homeScene”,即“addActivity”的前一个场景,并显示“addActivity”场景中的数据。
我尝试通过 map 将数据存储在“addActivity”场景中:
export const m = new Map();
并导入homeScene场景中的 map
import { m } from './addActivity';
我不确定这种方式是否好。我看到react-native-navigation有一些函数可以传递参数,但我不知道如何使用它们。 现在最大的问题是当我从“addActivity”场景中使用 goBack() 时如何刷新“homeScene”场景。 有两个场景的代码
homeScene.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
View,
TouchableOpacity,
Dimensions
} from 'react-native';
import { m } from './addActivity';
export default class LeftSideMenu extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: false,
}
add = () => {
const { navigate } = this.props.navigation;
navigate('Add');
}
render() {
return (
<View style={styles.container}>
//I want to show the data here
<Text
style={styles.btText2}>{m.get("title")}</Text>
//This is the bottom to jump to "addActivity" scene
<TouchableOpacity
onPress={this.add}
style={styles.Addbutton}>
<Text
style={styles.btText2}>+</Text>
</TouchableOpacity>
</View>
);
}
}
addActivity.js
import React, { Component } from 'react';
import { View, ScrollView, Dimensions, StyleSheet, Text, Button, TouchableOpacity, Alert } from 'react-native';
import { NavigationPage, ListRow, Input, Select, Label } from 'teaset';
let { height, width } = Dimensions.get('window');
//initial the map
export const m = new Map();
export default class InputExample extends Component {
constructor(props) {
super(props);
this.state = {
length: 0,
title: '',
isVisible: false,
};
Object.assign(this.state, {
valueTitle: null,
});
}
//Return to homeScene
homeScene = () => {
m.set("title", this.valueTitle);
const { goBack } = this.props.navigation;
Alert.alert("Add succeed","return to Homepage",[{text: 'confirm', onPress: () => { goBack(); }}])
}
render() {
return (
<ScrollView style={{ flex: 1 }}>
<ListRow title='Title *' detail={
<Input
style={{ width: 200 }}
size='md'
value={this.state.valueMD}
placeholder=''
onChangeText={text => this.setState({ valueTitle: text })}
/>
} topSeparator='full' />
<TouchableOpacity
onPress={this.homeScene}
style={styles.button}>
<Text
style={styles.btText}>Confirm</Text>
</TouchableOpacity>
</ScrollView>
);
}
}
我希望当我对 homeScene 使用 goBack() 时,场景可以刷新,并且来自 addActivity 场景的数据可以打印在 homeScene 上
最佳答案
为了刷新返回的上一个屏幕,您可以在要在从某个屏幕返回时更新组件状态的屏幕中使用此代码
componentDidMount()
this.getMoviesFromApiAsync()
this.props.navigation.addListener('willFocus',this._handleStateChange);
}
_handleStateChange = state => {
alert('Refreshed successfully!')
this.getMoviesFromApiAsync()
};
其中 getMoviesFromApiAsync()
是包含 API 调用代码的方法。
或 您可以使用 Redux 来实现相同的目的。
关于javascript - 当我 goBack() 时如何刷新上一个屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55884168/