Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  167] [ 6]  / answers: 1 / hits: 17656  / 8 Years ago, sun, july 3, 2016, 12:00:00

I am a newbie in React-Native. I want to select one item using ListView. When I first press item, the ListView renderRow() was call, But after all not working!How can I fix this bug? My problem is where?



I wrote a demo in here


More From » listview

 Answers
45

I ended up setting empty dataSource initially, then setting it to clone with data variable in componentDidMount. Then, in the onPressRow method, I made the required changes to a copy of data state variable and then set it back to data via setState method. Not sure what your problem was, but this is working now.



import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ListView,
TouchableHighlight
} from 'react-native';

class ListViewDemo extends Component {

constructor(props) {
super(props);

var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
data: this._genRow(),
dataSource: ds,
}
}

componentDidMount() {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(this.state.data)
});
}

_genRow(){
var datas = [];
for (var i = 0; i < 5; i++) {
datas.push({
row: i,
isSelect: false,
});
}
console.log('datas ' + JSON.stringify(datas));
return datas;
}

render() {
return (
<ListView
dataSource = {this.state.dataSource}
renderRow = {this._renderRow.bind(this)}
renderHeader = {() => <View style={{height: 10, backgroundColor: '#f5f5f5'}} />}
onEndReached = {() => console.log('')}
renderSeparator = {(sectionID, rowID) =>
<View
style={styles.style_separator}
key={`${sectionID} - ${rowID}`}
/>}
/>
);
}

_renderRow(rowData: string, sectionID: number, rowID: number) {
console.log('render row ...');
return (
<TouchableHighlight onPress={this._onPressRow.bind(this.rowID, rowData)}>
<View style={styles.style_row_view}>
<Text style={styles.style_text}>{rowData.row}</Text>
<Text style={styles.style_text}>{rowData.isSelect ? 'true' : 'false'} </Text>
</View>
</TouchableHighlight>
);
}

_onPressRow(rowID, rowData) {

rowData.isSelect = !rowData.isSelect;
var dataClone = this.state.data;
dataClone[rowID] = rowData;
this.setState({
data: dataClone
});
console.log(this.state.data);
}
}

const styles = StyleSheet.create({
style_row_view: {
flex: 1,
flexDirection: 'row',
height: 57,
backgroundColor: '#FFFFFF',
},
style_text: {
flex: 1,
marginLeft: 12,
fontSize: 16,
color: '#333333',
alignSelf: 'center',
},

});

AppRegistry.registerComponent('ListViewDemo', () => ListViewDemo);

[#61532] Thursday, June 30, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dallasb

Total Points: 657
Total Questions: 98
Total Answers: 97

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;