React Native 让 Flatlist 支持 选中多个值,并获取所选择的值
实现效果如下:
实现代码:
import React, {Component} from 'react';
import {
Image,
Text,
View,
TouchableOpacity,
FlatList,
StyleSheet,
Button
} from 'react-native'; export default class TestListCheck extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{
"id": "",
select: false
},
{
"id": "",
select: false
},
{
"id": "",
select: false
},
{
"id": "",
select: false
},
{
"id": "",
select: false
},
{
"id": "",
select: false
}
],//数据源
selectItem: [],
}
} _selectItemPress(item) {
if (item.select) {
this.state.selectItem.splice(this.state.selectItem.findIndex(function (x) {
return x === item.id;
}), );
} else {
this.state.selectItem.push(item.id);
}
this.state.data[item.id].select = !item.select;
this.setState({data: this.state.data})
} _submitPress() {
alert(`选中了${JSON.stringify(this.state.selectItem)}`)
} render() {
return (
<FlatList
keyExtractor={item => item.id}
data={this.state.data}
extraData={this.state} //这里是关键,如果不设置点击就不会马上改变状态,而需要拖动列表才会改变
ListHeaderComponent={({item}) => {
return (<Button title={"确定"} onPress={() => this._submitPress()}/>)
}}
renderItem={({item}) => {
return (
<View style={styles.standaloneRowFront}> <TouchableOpacity
onPress={() => this._selectItemPress(item)}>
<View style={styles.row}>
{item.select ?
<Image source={require('./ic_radio_checkbox_check.png')}
style={styles.imgCheckIcon}/>
:
<Image source={require('./ic_radio_checkbox_uncheck.png')}
style={styles.imgCheckIcon}/>
}
<View style={{marginLeft: }}>
<Text>{item.select ? ("选中") : ("未选中")}</Text>
</View>
</View>
</TouchableOpacity> </View>
)
}}
/>
);
}
}
const styles = StyleSheet.create({
standaloneRowFront: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#FFF',
height: ,
marginBottom:
},
imgCheckIcon: {
width: ,
height: ,
lineHeight: ,
},
row: {
flexDirection: "row",
alignItems: "center",
},
});
本博客地址: wukong1688
本文原文地址:https://www.cnblogs.com/wukong1688/p/11080603.html
转载请著名出处!谢谢~~