React Native中如何通过react-navigation跳转时触发目标页面按钮事件
问题解决:跳转后自动触发目标页面方法
核心问题分析
你当前的跳转写法this.props.navigation.navigate("MenuUtama", [ this.ButtonSection() ]);存在错误:ButtonSection是MenuUtama页面的专属方法,profile.js无法直接跨页面调用该方法。正确思路是跳转时传递触发标识,在目标页面加载时自动执行方法。
具体解决方案
1. 修改profile.js的跳转逻辑
在接口请求成功后,跳转时传递一个自定义参数,告知MenuUtama需要触发目标方法:
// profile.js中Submit方法的then回调部分 .then((res) => { Alert.alert("Success"); this.setState({ vLoader: false }); // 传递触发标识参数,替换原错误的跳转代码 this.props.navigation.navigate("MenuUtama", { triggerButtonSection: true }); })
注意:修正请求headers中的拼写错误——将
aplication/json改为application/json,避免请求格式异常。
2. 在MenuUtama页面监听并触发方法
如果是类组件,在生命周期方法中检测跳转参数,自动调用ButtonSection:
// MenuUtama页面代码 componentDidMount() { // 获取导航传递的参数 const { triggerButtonSection } = this.props.route.params || {}; // 如果存在触发标识,则执行目标方法 if (triggerButtonSection) { this.ButtonSection(); } } // 若需要处理从其他页面返回时的触发逻辑,可补充componentDidUpdate componentDidUpdate(prevProps) { const currentTrigger = this.props.route.params?.triggerButtonSection; const prevTrigger = prevProps.route.params?.triggerButtonSection; // 仅当触发标识变化时执行,避免重复调用 if (currentTrigger && currentTrigger !== prevTrigger) { this.ButtonSection(); } } ButtonSection = () => { this.getMitraId(); };
版本兼容说明
如果使用的是React Navigation旧版本(v4及以下),获取参数的方式改为:
const triggerButtonSection = this.props.navigation.getParam('triggerButtonSection', false);
内容的提问来源于stack exchange,提问作者Billie
相关产品推荐
相关产品推荐

