0
因此,我創建了一個循環,該循環遍歷由googles gecoding api創建的對象。查找某些值並將其放入「結果列表」中,單個元素具有onClick函數。現在,當我使用bind執行onClick函數時,他們確實能夠工作,當我用()=>他們不這樣做時。也許有人可以向我解釋爲什麼這不起作用?React循環遍歷對象並使用帶參數的onClick函數渲染div
循環:
renderResults: function(){
var status = this.state.data.status;
var results = this.state.data.results;
var ok = (status === 'OK' ? true : false);
if (!status) {
return <div> </div>
}
if (!ok) {
return <div className="searchresults">Error, we couldn't find a match</div>
}
if (status && ok){
var size = Object.keys(results).length
console.log(this.state.data);
var validation_messages = this.state.data.results;
///* Get properties *///
var resul =[];
for (var key in validation_messages) {
console.log("####### " + key + " #######");
// skip loop i the property is from prototype
if (!validation_messages.hasOwnProperty(key)) continue;
var label1 = '';
var label2 = '';
var obj = validation_messages[key];
console.log(obj);
for (var prop2 in obj.address_components) {
if(!obj.address_components.hasOwnProperty(prop2)) continue;
var obj3 = obj.address_components[prop2];
if (obj3.types.indexOf('locality') !== -1) {
label1 = obj3.long_name;
}
if (obj3.types.indexOf('country') !== -1) {
label2 = obj3.long_name;
}
}
var lat = obj.geometry.location.lat;
var lng = obj.geometry.location.lng;
var placeid = obj.place_id;
var label3 = lat.toFixed(3) + "°N/" + lng.toFixed(3) + "°E";
console.log('label1: '+label1);
console.log('label2: '+label2);
console.log('label3: '+label3);
console.log('lat: ' + lat);
console.log('lng: ' + lng);
console.log('id: ' + placeid);
console.log(validation_messages[key].formatted_address);
resul.push(<div className="results" onClick={this.pushlabels.bind(this, label1, label2, label3)} >{label3}</div>);
}
console.log(resul);
return resul;
}
所以此工程:
resul.push(<div className="results" onClick={this.pushlabels.bind(this, label1, label2, label3)} >{label3}</div>);
這不起作用:
resul.push(<div className="results" onClick={() => this.pushlabels(label1,label2,label3)} >{label3}</div>);
這是什麼意思有沒有工作?如果我採用的版本不起作用,我只能從循環中的最後一個對象中推送label1,label2,label3。
所以現在我想知道爲什麼?