5
var Restaurant = React.createClass({
resPress: function (resId, resName) {
    this.props.navigator.push({
        name: 'viewMenu',
        id: resId,
        placeName: resName
    });
},
render: function () {
    var that = this;
    return (
            <View>
                {this.state.place.map((item, i) => (<TouchableOpacity key={i} onPress={() => this.resPress(item.res_id, item.res_name)} ><Text>{item.res_name}</Text></TouchableOpacity>))}
            </View>
    )
}
});

This works perfectly fine. My question is why cant I just pass the values to the 'resPress' like mentioned below?

onPress={this.resPress(item.delivery_id, item.place_name)}
TA3
  • 382
  • 3
  • 5
  • 21

1 Answers1

26

You cannot call a function in render method, you can only pass a function as prop. for doing this there are two ways, 1. Using .bind, 2. Using arrow functions:

   <TouchableOpacity onPress={this.resPress.bind(this, yourData)} ><Text>{item.res_name}</Text></TouchableOpacity>


   <TouchableOpacity onPress={() => this.resPress(yourData)} ><Text>{item.res_name}</Text></TouchableOpacity>
  • 6
    You don't need to `bind` that function if you are already using the fat arrow. You can simply do: `onPress={(yourData) => this.resPress(yourData)}`. – Ferran Negre Sep 14 '16 at 11:44