javascript - 从常量中提取常量(变量的可访问性)
问题描述
使用 React Native 和 React Navigation,我可以更改我的标题navigationOptions
:
const ForumScreen = ({ navigation }) => {
const forum = navigation.getParam('forum')
...
}
IndexScreen.navigationOptions = () => {
return {
title: 'My Forum',
}
}
export default ForumScreen
但我想使用我的组件forum
变量。ForumScreen
我试过这个,但我得到了一个错误,因为变量不可访问:
...
IndexScreen.navigationOptions = () => {
return {
title: forum.name,
}
}
...
解决方案
您的示例forum
变量在 ForumScreen 函数的范围内定义,在外部不可用。
您可以尝试提升变量将其存储在 ForumScreen 和 IndexScreen 的父组件中(例如在 Redux Store 或顶级 React 组件中)
class Parent {
state = {
forum: null
}
setForum(forum) {
this.setState({ forum })
}
render() {
return (
<>
<ForumScreen setForum={this.setForum} />
<IndexForum forum={this.state.forum} />
</>
)
}
}
const ForumScreen = ({ setForum, navigation }) => {
const forum = navigation.getParam('forum')
setForum(forum):
...
}
我现在明白了,navigationOptions 是一个静态方法。它与 IndexScreen 无关this
。您必须将论坛作为参数传递,如下所示
IndexScreen.navigationOptions = (forum) => {
return {
title: forum.name,
}
}
或使 navigationOptions 非静态。
另一种方式,但不是 React 方式
let forum;
const ForumScreen = ({ navigation }) => {
forum = navigation.getParam('forum');
}
推荐阅读
- angular - 如何在不重新加载页面的情况下刷新角度 8 中的元素?
- angular - 角度材料选择可选的多项选择
- android - 获取 DocumentReferences 数组的实时更新
- css - 如何将两张引导卡并排放置
- macos - OS X Docker“在提取其状态之前重命名目录”的解决方法
- node.js - 在expressJS中获取Mongo数据库中插入文档的ID
- vbscript - 从 VBScript 中的文本文件中获取模式匹配值
- python - 我可以让一个方法成为一个生成器而不是返回一个吗?
- php - 嵌入图标的自定义文件列表而不是自定义目录列表
- mysql - 在这种情况下如何解决 MySQL 错误“#1242 - 子查询返回超过 1 行”?