【问题标题】:React Navigation Header in Functional Components with Hooks使用 Hooks 在功能组件中反应导航标题
【发布时间】:2019-09-08 00:21:15
【问题描述】:

我正在尝试将自定义标头注入到使用 Hooks 的 React 功能组件。

例如,我有以下带有一些钩子的 React 功能组件:

function StoryHome(props) {
  const [communityObj, setCommunityObj] = useState({
    uid: null,
    name: null,
  });
...
}

StoryHome.navigationOptions = {
  title: 'Stories',
  headerTitleStyle: {
    textAlign: 'left',
    fontFamily: 'OpenSans-Regular',
    fontSize: 24,
  },
  headerTintColor: 'rgba(255,255,255,0.8)',
  headerBackground: (
    <LinearGradient
      colors={['#4cbdd7', '#3378C3']}
      start={{ x: 0, y: 1 }}
      end={{ x: 1, y: 1 }}
      style={{ flex: 1 }}
    />
  ),
  headerRightContainerStyle: {  
    paddingRight: 10,   
  },    
  headerRight: (    
    <TouchableOpacity onPress={navigation.navigate('storiesList')}> 
      <Ionicons 
         name="ios-search-outline"  
         size={25}  
         color="white"  
         left={20}  
       />   
    </TouchableOpacity>
  )
};

export default StoryHome;

所以这种工作,除了TouchableOpacity 部分。

首先,我无法正确渲染 Ionicon,其次,我无法访问功能组件之外的 navigation 对象。

我很想继续使用 Hooks,但似乎无法解决这个问题。

【问题讨论】:

  • 你是如何在 createStackNavigator 中添加这个 StoryHome 的?
  • 像这样:export const StoryNavigator = createStackNavigator({ StoryHome: { screen: StoryHome }, StoryDetail: { screen: StoryDetail }, StoryList: { screen: StoryList }, });
  • 如果您使用的是导航 4:reactnavigation.org/docs/upgrading-from-4.x/…

标签: reactjs react-native header react-navigation


【解决方案1】:

navigationOptions 可以是一个以navigation 为属性获取对象作为参数的函数。

您还需要确保为onPress 提供函数,并且不要直接调用navigation.navigate

StoryHome.navigationOptions = ({ navigation }) => ({
  title: "Stories",
  headerTitleStyle: {
    textAlign: "left",
    fontFamily: "OpenSans-Regular",
    fontSize: 24
  },
  headerTintColor: "rgba(255,255,255,0.8)",
  headerBackground: (
    <LinearGradient
      colors={["#4cbdd7", "#3378C3"]}
      start={{ x: 0, y: 1 }}
      end={{ x: 1, y: 1 }}
      style={{ flex: 1 }}
    />
  ),
  headerRightContainerStyle: {
    paddingRight: 10
  },
  headerRight: (
    <TouchableOpacity onPress={() => navigation.navigate("storiesList")}>
      <Ionicons name="ios-search" size={25} color="white" left={20} />
    </TouchableOpacity>
  )
});

【讨论】:

  • 非常感谢,导航部分运行良好!唯一不起作用的是Ionicons 部分。我收到failed prop type invalid prop name
  • @esfoobar 太好了!不客气。我不确定如何在 React Native 中使用 Ionic 图标。该文档可能会帮助您弄清楚有哪些道具。
  • 非常感谢。看起来该图标名称在该反应本机库的 Ionicon 实现中不存在。将其更改为 ios-search 并且有效。再次感谢您!
  • 如果我想在navigationOptions 中的StoryHome 组件中传递一个钩子状态怎么办。我们该怎么做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多