通过在React Native

时间:2016-09-14 11:05:27

标签: javascript reactjs 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)}

1 个答案:

答案 0 :(得分:10)

你不能在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>
相关问题