How to associate an "onPress" event with the Button, TouchableOpacity, etc that generated it?

1.1k views Asked by At

In my React Native project using NativeBase I'd like to generate a series of Buttons or TouchableOpacities.

That means I don't want each to have a separate onPress handler but one shared one.

But when I look at what is passed to the onPress callback there doesn't seem to be any kind of ID or reference to the component that caused the press, nor can I find such a thing documented.

Am I missing something obvious? Is there another method everybody uses to achieve the same goal? Or is this actually missing functionality?

2

There are 2 answers

1
soutot On

You can try to use ref to identify a component

<Button ref={'loginButton'} onPress={this.onButtonPress()}>

Then you access it using this.refs['loginButton']

Hope it helps.

6
Vahid Boreiri On

You can use your function as below:

  _onPressButton = (id) = () => {
      // do something with id
  }

  _keyExtractor = (item, index) => index;


  _renderItem = ({item}) => (
    <Button onPress={this._onPressButton(item.d)}>
      ...
    </Button>
  );

  return (
    <FlatList
      data={data_array}
      keyExtractor={this._keyExtractor}
      renderItem={this._renderItem}
    />
  );