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

TA3*_*TA3 1 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>
    )
}
});
Run Code Online (Sandbox Code Playgroud)

这完全没问题.我的问题是为什么我不能将值传递给'resPress',如下所述?

onPress={this.resPress(item.delivery_id, item.place_name)}
Run Code Online (Sandbox Code Playgroud)

Ali*_*ade 14

请看这个链接.因为你可以传递一个函数.bind,你不能在它们内部执行一个函数.为了传递像this(.bind)语法这样的值,你必须这样做:

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


   <TouchableOpacity onPress={() => this.resPress(yourData)} ><Text>{item.res_name}</Text></TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)

  • 如果您已经使用了胖箭头,则不需要"绑定"该功能.你可以简单地做:`onPress = {(yourData)=> this.resPress(yourData)}`. (5认同)