react-nativereact-native-iosreact-native-router-fluxreact-native-listview

How to open other screen from react-native listview item


I am trying to open another screen when I do onPress on any item of the listview.

<TouchableHighlight underlayColor={AppColors.black}
                            onPress={Actions.SubCategoryList(item.guid)}>
        <View>
                 <Item style={{flexDirection: 'row', height: 50, borderBottomWidth: borderWidth}}>
                    <Text style={{
                        fontFamily: AppStyles.fontFamily,
                        fontSize: 17,
                        flex: 5,
                        color: AppColors.black
                    }}>{item.category_name}</Text>
                    <Item style={{flex: 1, borderBottomWidth: 0, flexDirection: 'row', justifyContent: 'flex-end'}}>
                        <Text style={{
                            color: AppColors.grey,
                            fontFamily: AppStyles.fontFamily,
                            fontSize: 17,
                            marginRight: 15
                        }}>{item.active_tournaments}</Text>
                        <Image resizeMode="contain" source={require('../../assets/images/right.png')}
                               style={{width: 15, height: 15, marginTop: 3}}/>
                    </Item>
                </Item>
            </View>
        </TouchableHighlight>

But whenever I came on current screen it directly goes on Subcategory screen without clicking.

And I want to know how to catch data send from the current screen on another screen.


Solution

  • the problem is that you are actually calling onPress immediately instead of setting it as a callback. You can see this in the following code:

    onPress={Actions.SubCategoryList(item.guid)}
    

    You have two options to fix this. Your first option is to add a function call in there like so:

    onPress={() => Actions.SubCategoryList(item.guid)}
    

    your second option is to change the Actions.SubCategoryList function to return a callback something like this:

    export function SubCategoryList(guid){
      return () => { // this gets called by onPress
    
        /* contents of function go here */
    
      }
    }
    

    Ideally for performance, you would also keep a cache of the callbacks you have created based on the guid, and return the cached copy instead of creating a new one. This is called memoization, and would look like this:

    let cache = {};
    export function SubCategoryList(guid){
      return cache[guid] || (cache[guid] = () => { 
    
        /* contents of function go here */
    
      })
    }