我有两个屏幕。家庭和照片详细信息。在家里我有照片列表。如果我喜欢PhotoDetails屏幕上的照片,我想在主屏幕上更新喜欢的内容。无需更新整个页面。我可以在屏幕之间使用回调吗?怎么样?我正在使用StackNavigator。 谢谢你的回答
<TouchableHighlight
onPress={() => navigate('PhotoDetails', {
id: rowData.caption.id,
tag: rowData.caption.text,
url: rowData.images.standard_resolution.url,
likes: this.state.likes[rowData.caption.id] || 0
})}>
<Image
source={{uri:rowData.images.standard_resolution.url}}
style={{width: 320, height: 320}}/>
</TouchableHighlight>
&#13;
<Like
onPress={()=> {onLike(this.state.id).then((newLikes)=>{
this.setState({
likes: newLikes
})
})}}
likes={this.state.likes + '' || '0'}
/>
&#13;
答案 0 :(得分:1)
在你的情况下,你应该将回调函数从主屏幕传递到子屏幕,它将更新值。例如:
class HomeScreen extends Component {
state = { likes: 0 }
callback(likes) {
this.setState({ likes: likes })
}
render() {
const navigation = this.props.navigation;
return (
<View>
<Text onPress={navigation.navigate('SomeChildScreen', { callback: this.callback.bind(this), likes: this.state.likes })}>Go to Child Screen</Text>
</View>
)
}
}
class SomeChildScreen extends Component {
liked() {
const navigation = this.props.navigation;
let likes = navigation.getParam('likes');
likes++;
navigation.getParam('callback')(likes);
navigation.navigate('HomeScreen');
}
render() {
const navigation = this.props.navigation;
return (
<View>
<Text onPress={this.liked}>Like</Text>
</View>
)
}
}
并注意我们必须如何传递回调函数: this.callback.bind(this)