简体   繁体   English

通过在React Native中触发onPress将值传递给方法

[英]Passing values to a method by triggering onPress in React Native

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? 我的问题是为什么我不能像下面提到的那样将值传递给'resPress'?

onPress={this.resPress(item.delivery_id, item.place_name)}

You cannot call a function in render method, you can only pass a function as prop. 您不能在render方法中调用函数,只能将函数作为prop传递。 for doing this there are two ways, 1. Using .bind , 2. Using arrow functions: 为此,有两种方法:1.使用.bind ; 2.使用箭头功能:

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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM