我正在使用 expo.io 构建一个 React Native 应用程序。
该应用程序正在使用堆栈导航器在页面(卡片)之间移动。
我的问题是,我有一个页面,用户可以在其中创建新项目,而我想在他们离开页面时保存这些项目。 我不想保存所有更改,而是想在离开页面之前提示用户是否要保存更改,以便他们有机会放弃所做的任何更改。
我无法找到退出页面的事件,我可以 Hook 并提示用户是否要保存更改? 我发现最接近我想做的事情是在backhandler中,但这仅适用于 Android 后退按钮。
如果用户使用卡片标题中的后退按钮返回,或者使用滑动手势返回,是否有办法执行类似的操作?
最佳答案
使用NavigationEvents 。将事件监听器添加到您的组件。
onWillFocus - event listener
onDidFocus - event listener
onWillBlur - event listener
onDidBlur - event listener
例如,当下一个屏幕聚焦时,将触发以下内容。在另一个屏幕中,将用户的更改保存在临时存储中,当他们返回时,获取那些未保存的更改并提示用户是否要保存或不是。
focusSubscription = null;
onWillFocus = (payload) => {
if (payload && payload.action && payload.action.type && payload.action.type === 'Navigation/BACK') {
// get values from storage here
// if there were unsaved changes prompt the user if they want to those changes or not
}
};
componentDidMount = () => {
this.focusSubscription = this.props.navigation.addListener(
'willFocus',
this.onWillFocus,
);
}
componentWillUnmount = () => {
this.focusSubscription && this.focusSubscription.remove();
this.focusSubscription = null;
};
关于reactjs - 在 react 应用程序中拦截返回事件以确认保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56467184/