示例
import React, {Component,} from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
FlatList,
} from 'react-native';
class MyListItem extends React.PureComponent {
onPress = () => {
this.props.onPressItem(this.props.id);
};
render() {
const textColor = this.props.selected ? "red" : "black";
let text={
color: textColor,
fontSize:20,
};
return (
<TouchableOpacity onPress={this.onPress}>
<View>
<Text style={text}>
{this.props.id}
{this.props.title}
</Text>
</View>
</TouchableOpacity>
);
}
}
export class pageComponent extends React.PureComponent {
constructor(props) {
super(props);
let selectedData=new Map();
selectedData.set(1,true);
selectedData.set(2,false);
this.state = {
selected:selectedData,
data:[
{id:1,title:'我第一条数据,可以点击我'},
{id:2,title:'我第二条数据,可以点击我'},
{id:3,title:'我第三条数据,可以点击我'},
]
}
}
keyExtractor = (item, index) => item.id;
onPressItem = (id) => {
this.setState((state) => {
const selected = new Map(state.selected);
selected.set(id, !selected.get(id));
return {selected};
});
};
renderItem = ({item}) => (
<MyListItem
id={item.id}
onPressItem={this.onPressItem}
selected={!!this.state.selected.get(item.id)}
title={item.title}
/>
);
render() {
return (
<FlatList
style={styles.container}
data={this.state.data}
extraData={this.state}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
/>
);
}
}
const styles = StyleSheet.create({
container:{
flex:1,
marginTop:100
}
});