Vinh
Vinh

Reputation: 73

onPress parameters doesn't change

I want to display a list of item and when I click each item, it will alert me it's value.

_onPressButton(i) { 
    Alert.alert('You tapped the button number ' + i)
}

_renderBlockLebel = (number) => {
    var items = [];
    for (var i=0; i < number; i++) { 
        items.push(
            <TouchableOpacity onPress={() => this._onPressButton(i)} key={i}>
                <View style={styles.boxItem}>
                    <Text>Level {i}</Text>
                </View>
            </TouchableOpacity>
        );
    }
    return items;
}

render(){
    return(
        <View style={styles.box}>{this._renderBlockLebel(18)}</View>
    );
}

I have 18 items, it displays nice but when I click at any items, it alert "You tapped the button number 18", the value I passed is not change.

What is wrong with my code? I am new to React Native.

Upvotes: 0

Views: 290

Answers (2)

Gaspar Teixeira
Gaspar Teixeira

Reputation: 1267

I tried to consider a variable and it works.

import * as React from 'react';
import { Alert, TouchableOpacity, Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';

export default class App extends React.Component {
  _onPressButton (n) {
    Alert.alert('You tapped the button number ' + n);
  }

  _renderBlockLebel = number => {
    var items = [];
    for (var i = 0; i < number; i++) {
      const n = i;
      items.push(
        <TouchableOpacity onPress={() => this._onPressButton(n)} key={i}>
          <View style={styles.boxItem}>
            <Text>Level {i}</Text>
          </View>
        </TouchableOpacity>
      );
    }
    return items;
  };

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.box}>{this._renderBlockLebel(18)}</View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
});

https://snack.expo.io/@gasparteixeira/alert-number

enter image description here

Upvotes: 1

Prasun
Prasun

Reputation: 5023

When you are pressing the label, the value of i has reached to number (which is 18 is your case). You need to retain the value of i with each iteration. Change the _onPressButton declaration as

_onPressButton = (i) => () => { 
    Alert.alert('You tapped the button number ' + i)
}

Also change the onPress handler to

<TouchableOpacity onPress={this._onPressButton(i)} key={i}>

Have a look at the closure.

Hope this will help!

Upvotes: 2

Related Questions