结合Redux导航到其他屏幕

时间:2020-10-25 21:07:24

标签: reactjs react-native redux

我对组件有以下要求

    <div class="slideshow-container">

     <!-- Full-width images with number and caption text -->
     <div class="mySlides fade">
       <img src="https://earthsky.org/upl/2016/05/stars-nasa-sq-300x300.jpg" style="width:100%">
     </div>

     <div class="mySlides fade">
       <img src="https://miro.medium.com/max/4514/1*eyuCr9KOhADGM7V4-4Mt8Q.jpeg" style="width:100%">
     </div>

    <div class="mySlides fade">
    <img src="https://earthsky.org/upl/2016/05/stars-nasa-sq-300x300.jpg" style="width:100%">
    </div>

    <!-- Next and previous buttons -->
    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>
     </div>
     

Restaurant.js:

RestaurantTemplate :
import React from 'react';
import { StatusBar } from 'expo-status-bar';
import { ImageBackground, StyleSheet, View,TouchableOpacity} from 'react-native';
import { RestaurantData } from '../../Data';
import { connect } from 'react-redux';
import Restaurant from './Restaurant';

class RestaurantOverviewTemplate extends React.Component{
    render() {
        return(
            <View style={{ flex: 1, justifyContent: 'center' }}>
                <Restaurant restaurants={RestaurantData} onPress={this.props.changeToRestaurantId}/>
            </View>
        )
    }
}

const  mapDispatchToProps = (dispatch) => {
    return {
        changeToRestaurantId: (restaurants) => dispatch({ type: 'UPDATE_ID', payload: restaurants })
    }
}

export default connect(null, mapDispatchToProps)(RestaurantOverviewTemplate);

所以我有import React from 'react'; import { View, Text, Button, StyleSheet } from 'react-native'; export default class Restaurant extends React.Component { renderRestaurant = (restaurants) =>{ return restaurants.map((item, index) => { return( <View key={ index }> <Button onPress={ () => this.props.onPress(item.id) } title={ item.name }/> </View> ) }); } render() { return ( <View> {this.renderRestaurant(this.props.restaurants)} </View> ) } } 组件在其中导入的RestaurantTemplate。我的目的是提取饭店的ID,并将其传递给用于更新全局变量的Restaurant.js函数。但是我的问题是,当按下一个餐厅时,我想导航到另一个屏幕。我以为可以这样做:

mapDispatchToProps

但是这行不通。我也无法在<Restaurant restaurants={RestaurantData} onPress={[this.props.changeToRestaurantId, () => this.props.navigation.navigate('RestaurantDetails']} /> 周围包裹一个TouchableOpacity。 有谁知道我该如何解决?

提前谢谢!

1 个答案:

答案 0 :(得分:0)

似乎您要在回调中调用多个函数。您可以将两个调用都包装在一个匿名函数中。将传递的餐厅ID代理到changeToRestaurantId并调用导航。当然,这假设您已将navigation作为道具正确地注入到RestaurantOverviewTemplate组件中。

<Restaurant
  restaurants={RestaurantData}
  onPress={(id) => {
    this.props.changeToRestaurantId(id); 
    this.props.navigation.navigate('RestaurantDetails');
  }}
/>