reactjs - 为什么 react-navigation 的 setParams() 在一个组件中工作而不是在另一个组件中工作?
问题描述
我在我的 react-native 应用程序的标题中设置了一个可触摸的 onPress 函数。本项目使用 react-navigation (v4) 功能是打开分享对话框。它在一个组件中完美运行,而完全相同的代码在另一个组件中根本不起作用,引发未定义的错误。
工作画面:
class WorkingScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerRight: () => (
<TouchableOpacity onPress={navigation.state.params.onShare}>
<Image
source={require('../assets/img/white-share.png')}
style={{ height: 20, width: 20, marginRight: 20 }}
resizeMode={'contain'}
/>
</TouchableOpacity>
)
}
}
{...}
componentDidMount() {
this.props.navigation.setParams({ onShare: () => this._onShare() })
}
_onShare = async () => {
const uid = this.props.navigation.getParam('uid')
const options = { title: uid, message: 'buggy af react-navigation' }
Share.open(options)
.then((res) => {
console.log(res);
})
.catch((err) => {
err && console.log(err);
});
}
{...}
}
工作屏幕路由配置:
Working: {
screen: WorkingScreen,
navigationOptions: () => ({
title: 'Working'
})
}
非工作屏幕:
class NotWorkingScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerLeft: () => (
<TouchableOpacity onPress={() => navigation.toggleDrawer()}>
<Image
source={require('../assets/img/menu.png')}
style={{ marginLeft: 20, height: 20, width: 25 }}
resizeMode={'contain'}
/>
</TouchableOpacity>
),
headerRight: () => (
<TouchableOpacity onPress={navigation.state.params.onShare}>
<Image
source={require('../assets/img/white-share.png')}
style={{ height: 20, width: 20, marginRight: 20 }}
resizeMode={'contain'}
/>
</TouchableOpacity>
)
}
}
componentDidMount() {
this.props.navigation.setParams({ onShare: () => this._onShare() })
}
{...}
_onShare = async () => {
const uid = this.props.navigation.getParam('uid')
const options = { title: uid, message: 'buggy af react-navigation' }
Share.open(options)
.then((res) => {
console.log(res);
})
.catch((err) => {
err && console.log(err);
});
}
{...}
}
非工作屏幕路由配置:
NotWorking: {
screen: NotWorkingScreen,
navigationOptions: () => ({
title: 'Not Working'
})
}
非工作屏幕的崩溃是:
TypeError:未定义不是对象(评估“navigation.state.params.onShare”)
它们具有相同的堆栈配置。我不知道这是怎么回事。有任何想法吗?
解决方案
推荐阅读
- python - 如何从字符串中删除我想要的所有内容?
- python - 如何在不关闭应用程序的情况下停止功能?
- javascript - 如何在 Vue.js 应用程序中获取 Fullcalendar 的视图对象
- css - 如何使背景图像适合父元素?
- javascript - UnhandledPromiseRejection 未定义问题
- sql - 如何解决错误“结果:滥用聚合函数 json_group_array()”?
- amazon-web-services - K8S EKS Cluster Autoscaler 无需资源请求即可工作
- reactjs - 使用 Hooks 在 React Js 中切换问题
- whatsapp - 通过 GupShup 提交的 Whatsapp 消息模板被 whatsapp 拒绝
- python - 如何正确地将 csv 从 Express js 发送到 python 代码?