【问题标题】:Extract a constant from a constant (accessibility of variables)从常量中提取常量(变量的可访问性)
【发布时间】:2020-03-29 08:24:41
【问题描述】:

使用 React Native 和 React Navigation,我可以使用 navigationOptions 更改我的标题:

const ForumScreen = ({ navigation }) => {
  const forum = navigation.getParam('forum')

  ...
}

IndexScreen.navigationOptions = () => {
  return {
    title: 'My Forum',
  }
}

export default ForumScreen

但我想使用ForumScreen 组件的forum 变量。

我试过了,但我得到了一个错误,因为变量不可访问:

...
IndexScreen.navigationOptions = () => {
  return {
    title: forum.name,
  }
}
...

【问题讨论】:

  • FourmScreen的返回值是多少?

标签: javascript react-native ecmascript-6


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-07-27
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    相关资源
    最近更新 更多