【问题标题】:Question about custom header in React Navigation v5 (Not clickable back button)关于 React Navigation v5 中自定义标题的问题(不可点击的后退按钮)
【发布时间】:2020-03-10 22:06:45
【问题描述】:

您好,我正在使用 React 导航 v5。 我正在尝试为特定屏幕实现自定义标题。所以我的自定义标题看起来像这样

CustomHeader.js

export function CustomHeader({props}) {
  const {scene, previous, navigation} = props;
  const opacity = scene.route.params.opacity;

  return (
    <React.Fragment>
      <Animated.View style={[styles.headerStyle, {opacity}]}>
        <View style={styles.influencerNameContainer}>
          <Text style={styles.influencerName}>
            {scene.route.params.influencer.user.name}
          </Text>
        </View>
      </Animated.View>

      {previous ? (
/* This is a back button */
        <Button
          style={[styles.iconButton, {left: 0}]}
          icon={BackIcon}
          onPress={() => {navigation.goBack}
        />
      ) : (
        undefined
      )}
    </React.Fragment>
  );
}

导航器长这样

export function HomeStack() {
  return (
    <Stack.Navigator
      initialRouteName="Home"
      headerMode="screen"
      style={{backgroundColor: 'yellow'}}>

      <Stack.Screen
        name="InfluencerScreen"
        component={InfluencerScreen}
        options={{
          header: props => <CustomHeader props={props} />,
        }}
      />
    </Stack.Navigator>
  );
}

它呈现自定义标题和自定义后退按钮,但后退按钮不可点击。 所以我尝试了。

<Stack.Screen
        name="InfluencerScreen"
        component={InfluencerScreen}
        options={{
          header: props => <CustomHeader props={props} />,
          headerLeft: () => (
            <Button title="Back Button" onPress={() => alert('Pressed')} />
          )
        }}
      />

使用此代码,它根本不会显示带有自定义标题的后退按钮。但是当我删除自定义标题(标题:道具=>)时,它会显示自定义后退按钮。

我错过了什么?

【问题讨论】:

    标签: reactjs react-native react-navigation react-navigation-v5


    【解决方案1】:

    您正在显示自定义标题,如何呈现按钮取决于您。 React Navigation 无法显示后退按钮,因为 React Navigation 不再呈现标题。

    您需要将后退按钮放在自定义标题中,而不是使用headerLeft 选项。

    您的解构也不正确。 function CustomHeader({props}) 应该是 function CustomHeader(props)(不带花括号)。

    【讨论】:

      【解决方案2】:

      你正在解构props 两次.. 尝试:

      export function CustomHeader({scene, previous, navigation}) {
      
        // const {scene, previous, navigation} = props; // remove this
      
        ...
      
      }
      

      编辑:

      另外goBack 是一个方法,所以用括号调用它:

      onPress={() => navigation.goBack()} // remove unnecessary `curly braces`
      

      【讨论】:

        猜你喜欢
        • 2017-08-14
        • 2021-05-01
        • 2022-09-24
        • 1970-01-01
        • 1970-01-01
        • 2023-02-01
        • 2021-11-25
        • 2013-09-23
        相关资源
        最近更新 更多