【问题标题】:How to use React Navigation with an element inside of a FlatList's Header?如何将 React Navigation 与 FlatList 的 Header 内的元素一起使用?
【发布时间】:2021-04-06 04:43:29
【问题描述】:

我可以在 renderItem 中完美导航,但是当我尝试在我在标题中使用的组件中单击时显示“未定义不是对象(正在评估 '_this.props.navigation.navigate')

这就是我试图在传递给 FlatLists 标题的组件中导航的方式 <TouchableOpacity onPress={() => this.props.navigation.navigate('Profile', { data: info })}>

【问题讨论】:

  • 你能在这里发送更多带有标头代码的代码吗?
  • 请提供可重现的代码

标签: react-native react-navigation react-native-flatlist flatlist


【解决方案1】:

我通过导航道具传递给 ListHeaderComponent,它可以工作,因为渲染的元素给我带来了一些其他问题

我就是这样做的

return(
            <SafeAreaView style={styles.container}>
                <FlatList
                    ListHeaderComponent={
                        <>
                            <Header navigation={this.props.navigation}/>
                        </>
                    }
                    style={styles.scrollView}
                    numColumns='2'
                    columnWrapperStyle={{justifyContent: 'space-between'}}
                    data={ex}
                    renderItem={renderItem}
                    keyExtractor={(item, index) => index.toString()}
                />
            </SafeAreaView>
        );

【讨论】:

    【解决方案2】:

    只是一种预感,但我的猜测是组件被传递给 ListHeaderComponent 而不是带有 navigation 属性的渲染元素。

    例如:

    function Parent(props) {
      // Here the FlatList will render the header as <MyHeader /> with no props
      // If this.props.navigation is called in MyHeader it will be undefined
      return (
        <FlatList ListHeaderComponent={MyHeader} ... />
      );
    }
    

    function Parent(props) {
      // here MyHeader is rendered as an element first, passing through
      // the necessary navigation prop
      const headerElement = (<MyHeader navigation={props.navigation} />);
      return (
        <FlatList ListHeaderComponent={headerElement} ... />
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2021-02-09
      • 2018-01-29
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多