簡體   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>
    )
}
});

這工作得很好。 我的問題是為什么我不能像下面提到的那樣將值傳遞給'resPress'?

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

您不能在render方法中調用函數,只能將函數作為prop傳遞。 為此,有兩種方法: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