【问题标题】:how to render conditionally within the react native stack navigator header?如何在反应本机堆栈导航器标题中有条件地呈现?
【发布时间】:2018-03-09 00:55:45
【问题描述】:

我正在尝试根据导航参数有条件地呈现 headerRight。我目前正在静态导航选项中尝试这个。这是我的代码,但没有任何内容呈现到屏幕上

static navigationOptions = ({navigation}) => ({
headerRight : () => {
  if (navigation.state.params.user.following) {
    return (
        <TouchableOpacity
          onPress={() => this.followUser()}>
          <Icon2 name="ios-person-add-outline" size={35} />
        </TouchableOpacity>
    )}  else {
    return (
          <TouchableOpacity
            onPress={() => this.unfollowUser()}>
            <Icon name="user-times" size={20} />
          </TouchableOpacity>
        )}
    },
})

可以这样做还是我需要在此处使用自定义标题?

任何帮助将不胜感激!谢谢!

解决方案:

去掉匿名函数,实现soutot推荐的条件语法

static navigationOptions = ({navigation}) => ({
  headerRight :  navigation.state.params.otherUser.following ?
    ( <TouchableOpacity
         onPress={() => this.followUser()}>
         <Icon2 name="ios-person-add-outline" size={35} />
      </TouchableOpacity> )
    :
    ( <TouchableOpacity
         onPress={() => this.unfollowUser()}>
         <Icon name="user-times" size={20} />
      </TouchableOpacity> )
    })

【问题讨论】:

  • 哪些行显示了意外的令牌?在触发导航之前检查是否传递了user 参数?
  • 对不起,这应该已经被编辑了,因为它现在没有抛出意外的令牌。相反,它没有渲染任何东西。编辑以反映这一点。

标签: react-native conditional-rendering stack-navigator


【解决方案1】:

您在“else”语句后使用逗号 (,)。你也可以试试这样的

return(
navigation.state.params.user.following ?
<TouchableOpacity
  onPress={() => this.followUser()}>
  <Icon2 name="ios-person-add-outline" size={35} />
</TouchableOpacity>
:
<TouchableOpacity
  onPress={() => this.unfollowUser()}>
  <Icon name="user-times" size={20} />
</TouchableOpacity>
);

有关条件渲染的更多信息,请查看以下文档: https://facebook.github.io/react/docs/conditional-rendering.html

https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

希望对你有帮助

【讨论】:

  • 这在我删除匿名函数并添加括号后有效!谢谢!
  • 我可以在 onPress 中添加条件吗?并有条件地导航到不同的屏幕?
  • 是的,你可以。 onPress 接收一个函数。您可以根据需要向其中添加任何逻辑。因此,在给定的示例中,可以添加如下条件:onPress={() =&gt; navigation.state.params.user.following ? this.followUser() : this.unfollowUser()}。希望对你有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 2019-12-16
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
相关资源
最近更新 更多