在JavaScript中this是有作用域的,先看代码
import React, {
Component
} from 'react';
import {
StyleSheet,
View,
Text,
ListView,
TouchableHighlight,
Alert,
} from 'react-native';
class IndexView extends Component {
constructor(props) {
super(props);
var ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 != r2
});
this.state = {
dataSource: ds.cloneWithRows([
'1111111', '222222', '333333', '444444', '555555', '666666', '777777', '888888', '999999', '000000', '123457',
])
};
this._renderRow = this.renderRow.bind(this);
this._renderSeparator = this.renderSeparator.bind(this);
this._rowPressed = this.rowPressed.bind(this);
}
render() {
return (
<ListView
style={{flex:1, backgroundColor: 'white',}}
dataSource={this.state.dataSource}
renderRow={this._renderRow}
renderSeparator = {this._renderSeparator}
/>
);
}
renderRow(rowData,sectionID,rowID,highlightRow) {
return (
<TouchableHighlight
onPress={() => {
this._rowPressed(sectionID, rowID);
highlightRow(sectionID, rowID);
}
}
style={{}}
underlayColor='red'>
<View style={{flexDirection: 'row',justifyContent: 'center',backgroundColor: '#F6F6F6',}}>
<Text style={{fontSize: 18}}>
{rowData}
</Text>
</View>
</TouchableHighlight>
);
}
renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
return(
<View key={`${sectionID}-${rowID}-renderSeparator`} style={{flex:1, height: .5,backgroundColor: '#c0c0c0'}}>
</View>
);
}
rowPressed(sectionID,rowID) {
Alert.alert('标题','内容');
}
}
const styles = StyleSheet.create({
});
export default IndexView;
renderRow方法内部用到了this,其实renderRow这个方法的调用者是ListView这个类,那么在renderRow内部的this就不在是当前你所需要的this了,解决方法就是在初始化的时候bind,其他几个方法同理