這個單選功能使用的是Ant Design Mobile RN庫中的Radio實現的,效果如圖
話不多說講直接上代碼
1、引入import { Radio} from '@ant-design/react-native';
2、聲明 const RadioItem = Radio.RadioItem;
3、state中
state = { bidDocId: 0, // 選中數據 selIndex: 0, // 選中索引 };
4、使用map實現
// 使用map實現單選 private showMap() { let dataList: any[] = this.state.data if (dataList && dataList.length) { return dataList.map((item, index) => { return ( <RadioItem key={index} style={{ height: 70 }} checked={this.state.selIndex === index} onChange={(event: any) => { // 如果選中則更新數據 if (event.target.checked) { this.setState({ selIndex: index }); this.state.bidDocId = item.bidDocId } }} > {/* 自定義控件 */} <View style={{ flex: 1, paddingVertical: 15, flexDirection: 'row' }}> <SelBidderView bidderHeadImg={item.iconUrl} bidderName={item.userName} /> </View> </RadioItem> ); }) } }
5.使用FlatList實現單選
// 使用FlatList實現單選 private showFlatList() { let dataList = this.state.data if (dataList && dataList.length) { const extraUniqueKey = () => Math.random().toString(); const renderAssertItem = (render: ListRenderItemInfo<any>) => { return ( <View> <RadioItem checked={this.state.selIndex === render.index} onChange={(event: any) => { // 如果選中則更新數據 if (event.target.checked) { this.setState({ selIndex: render.index }); this.state.bidDocId = render.item.bidDocId } }} > <View style={{ marginVertical: 15 }}> <SelBidderView bidderHeadImg={render.item.iconUrl} bidderName={render.item.userName} /> </View> </RadioItem> </View> ) } return ( <FlatList //數據綁定 data={dataList} //列表顯示控件 renderItem={renderAssertItem} keyExtractor={extraUniqueKey} /> ); } }