【问题标题】:Passing values to a method by triggering onPress in React Native通过触发 React Native 中的 onPress 将值传递给方法
【发布时间】:2017-01-22 04:01:15
【问题描述】:
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)}

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    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>
    

    【讨论】:

    • 如果您已经在使用粗箭头,则不需要bind 该函数。你可以这样做:onPress={(yourData) =&gt; this.resPress(yourData)}.
    猜你喜欢
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    相关资源
    最近更新 更多