首页 > 解决方案 > 在 React Native 中将参数向下传递四级

问题描述

在我的App.js文件中,我创建了堆栈导航器:

<Stack.Navigator
    screenOptions={{
      headerShown: false,
    }}
    initialRouteName={'BookListingScreen'}>
    <Stack.Screen name="Book List" component={Tabs} />
    <Stack.Screen
      name="BookDetailScreen"
      component={BookDetailScreen}
    />
  </Stack.Navigator>

然后在我使用 redux 的图书列表屏幕上,我调用了this.props.navigation.navigateon 函数:

class BookListingScreen extends Component {
  componentDidMount() {
    this.props.fetchBooks();
  }

  onPressHandler = () => {
    this.props.navigation.navigate('BookDetailScreen');
  };

  render() {
    let content = (
      <BookList
        onPressHandler={this.onPressHandler}
        books={this.props.randomBooks.books}
      />
    );
    if (this.props.randomBooks.isFetching) {
      content = <ActivityIndicator size="large" />;
    }
    return (
      <View style={styles.container}>
        <View>{renderHeader()}</View>
        <View>{content}</View>
      </View>
    );
  }
}

正如您在我的身上看到的,我onPressHandler没有通常具有如下对象数据的对象:this.props.navigation.navigate('BookDetailScreen', {object data});

然后在我的书单组件上,我收到导航并通过以下方式传递数据项onPressHandler={this.props.onPressHandler(item)}

<FlatList
        style={{flex: 1}}
        data={this.props.books}
        keyExtractor={this._keyExtractor}
        renderItem={({item} = this.props.books) => {
          return (
            <BookItem
              onPressHandler={this.props.onPressHandler(item)}
              item={item}
            />
          );
        }}
      />

最后在我的 BookItem 上,我调用了这个onPress函数:

<TouchableOpacity onPress={() => this.props.onPressHandler(item)}>
        <View style={styles.cardContainerStyle}>
          <View style={{paddingRight: 5}}>
            <Text style={styles.cardTextStyle}>{title}</Text>
          </View>
        </View>
      </TouchableOpacity>

所以在我的详细信息屏幕上,我正在尝试接收和输出数据:

View style={{marginTop: 80}}>
        <Text>Detail Screen</Text>
        <Text>{this.props.params.item.title}</Text>
      </View>

但这返回了一个未定义的对象,评估为this.props.params.item

知道如何解决这个问题并能够从导航接收项目数据吗?

标签: javascriptreactjsreact-native

解决方案


推荐阅读