转到React-Native Flatlist中的详细信息页面

问题描述 投票:0回答:1

单击一行时,我制作了一个Flatlist导航到详细信息屏幕。

我创建了4个文件。

菲尔1:

index.js

import React from 'react';
import List from "./list";
import Detail from "./detail";
import { createStackNavigator, createAppContainer } from "react-navigation";

const AppNavigator = createStackNavigator({
  ListScreen: {
    screen: List,
  },
  DetailScreen: {
    screen: Detail,
  },
}, {
    initialRouteName: 'ListScreen',
});

export default createAppContainer(AppNavigator);

和detail.js

export default class DetailScreen extends React.PureComponent  {
    render() {
      return (
        <View
          <Text>Home Details!</Text>
        </View>
      );
    }
}

list.js

    import Products from "./products";
    export default class ListScreen extends React.PureComponent  {
      ...

      renderItem({ item }) {
          return <Products product={item}/>
      }

      render() {
        return (

            <View style={{margin:5}}>
              <FlatList
                 data={this.state.products}
                 renderItem={this.renderItem}
                 keyExtractor={(item,index) => item.id.toString()}
              />
            </View>

        );
      }

最后

products.js

export default class ProductsType2 extends React.PureComponent {
  _onPress = () => {
    this.props.navigation.navigate('DetailScreen', this.props.product.id);
  };

  render() {
    const { product} = this.props;
    //const { navigate } = this.props.navigation; //get error w
    return (
      <Card>
          <CardItem cardBody button onPress={this._onPress}>
            <Image
              style={{height: 140, width: 140, flex: 1}}
              source={{uri: product.thumbnail}} />
          </CardItem>
        </Card>
      );
   }
}

当我按下它时,我无法显示细节屏幕。

我收到此错误:

无法读取undefined的属性'navigate'

react-native react-navigation react-native-flatlist
1个回答
1
投票

使用withNavigation(HOC)从products.js访问导航道具。该组件不在createStackNavigator内部,因此使用withNavigation方法导出您的类,您可以访问导航道具。

import { withNavigation } from 'react-navigation';

...

export default withNavigation(ProductsType2)

https://reactnavigation.org/docs/en/connecting-navigation-prop.html

© www.soinside.com 2019 - 2024. All rights reserved.