首页 > 解决方案 > 从常量中提取常量(变量的可访问性)

问题描述

使用 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,
  }
}
...

标签: javascriptreact-nativeecmascript-6

解决方案


您的示例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');
}

推荐阅读