Example code of the react native indexed city list component, reactnative

Source: Internet
Author: User

Example code of the react native indexed city list component, reactnative

City list selection is a common feature of many apps, such as a typical meitu app. So how can we implement React Native?

To achieve the above results, you must first make a simple analysis of the composition of the interface, the interface data mainly consists of the current city, historical access city and popular city, therefore, when providing Json data, we need to divide the data into at least three parts.

const ALL_CITY_LIST = DATA_JSON.allCityList;const HOT_CITY_LIST = DATA_JSON.hotCityList;const LAST_VISIT_CITY_LIST = DATA_JSON.lastVisitCityList;

To implement the letter index function, we need to customize a control to bind data. The custom component code is as follows:

CityIndexListView. js

'Use strict '; import React, {Component} from 'react'; import {StyleSheet, View, Text, TouchableOpacity, ListView, Dimensions,} from 'react-native '; import Toast, {DURATION} from '. /ToastUtil 'const SECTIONHEIGHT = 30; const ROWHEIGHT = 40; const ROWHEIGHT_BOX = 40; var totalheight = []; // the total height of the city and letter corresponding to each letter const {width, height} = Dimensions. get ('window'); var that; const key_now = 'current '; const key_last_visit = 'Latest'; const key_hot = 'hot top'; export default class CityIndexListView extends Component {constructor (props) {super (props); var getSectionData = (dataBlob, sectionID) =>{ return sectionID;}; var getRowData = (dataBlob, sectionID, rowID) =>{ return dataBlob [sectionID] [rowID] ;}; let ALL_CITY_LIST = this. props. allCityList; let CURRENT_CITY_LIST = this. props. nowCityList; let LAST_VISIT_CITY_LIST = th Is. props. lastVisitCityList; let HOT_CITY_LIST = this. props. hotCityList; let letterList = this. _ getSortLetters (ALL_CITY_LIST); let dataBlob ={}; dataBlob [key_now] = CURRENT_CITY_LIST; dataBlob [key_last_visit] = keys; dataBlob [key_hot] = HOT_CITY_LIST; ALL_CITY_LIST.map (cityJson => {let key = cityJson. sortLetters. toUpperCase (); if (dataBlob [key]) {let subList = dataBlob [key]; subL Ist. push (cityJson);} else {let subList = []; subList. push (cityJson); dataBlob [key] = subList ;}}); let sectionIDs = Object. keys (dataBlob); let rowIDs = sectionIDs. map (sectionID => {let thisRow = []; let count = dataBlob [sectionID]. length; for (let ii = 0; ii <count; ii ++) {thisRow. push (ii);} let eachheight = SECTIONHEIGHT + ROWHEIGHT * thisRow. length; if (sectionID === key_hot | sectionID === Key_now | sectionID === key_last_visit) {let rowNum = (thisRow. length % 3 = 0 )? (ThisRow. length/3): parseInt (thisRow. length/3) + 1; console. log ('sectionids ==>' + sectionIDs + ", rowNum ====>" + rowNum); eachheight = SECTIONHEIGHT + ROWHEIGHT_BOX * rowNum;} totalheight. push (eachheight); return thisRow;}); let ds = new ListView. dataSource ({getRowData: getRowData, getSectionHeaderData: getSectionData, rowHasChanged: (row1, row2) => row1! = Row2, sectionHeaderHasChanged: (s1, s2) => s1! = S2}); this. state = {dataSource: ds. cloneWithRowsAndSections (dataBlob, sectionIDs, rowIDs), letters: sectionIDs}; that = this ;}_ getSortLetters (dataList) {let list = []; for (let j = 0; j <dataList. length; j ++) {let sortLetters = dataList [j]. sortLetters. toUpperCase (); let exist = false; for (let xx = 0; xx <list. length; xx ++) {if (list [xx] = sortLetters) {exist = true;} if (exist ){ Break;} if (! Exist) {list. push (sortLetters) ;}} return list;} _ cityNameClick (cityJson) {// alert ('selected city ====' + cityJson. id + '#####' + cityJson. name); this. props. onSelectCity (cityJson);} _ scrollTo (index, letter) {this. refs. toast. close (); let position = 0; for (let I = 0; I <index; I ++) {position + = totalheight [I]} this. _ listView. scrollTo ({y: position}); this. refs. toast. show (letter, DURATION. LENGTH_SHORT);} _ renderRightLetters (letter, index) {return (<TouchableOpacity key = {'Letter _ idx _ '+ index} activeOpacity = {0.6} onPress = {() => {this. _ scrollTo (index, letter) }}> <View style = {styles. letter }> <Text style = {styles. letterText >{letter }</Text> </View> </TouchableOpacity>);} _ renderListBox (cityJson, rowId) {return (<TouchableOpacity key = {'list _ item _ '+ cityJson. id} style = {styles. rowViewBox} onPress = {() => {that. _ cityNameClick (cityJson) }}> <View style = {styles. rowdataBox }> <Text style = {styles. rowDataTextBox >{cityjson. name} </Text> </View> </TouchableOpacity>);} _ renderListRow (cityJson, rowId) {console. log ('rowid => '+ rowId + ", cityJson =>" + JSON. stringify (cityJson); if (rowId = key_now | rowId = key_hot | rowId = key_last_visit) {return that. _ renderListBox (cityJson, rowId);} return (<TouchableOpacity key = {'list _ item _ '+ cityJson. id} style = {styles. rowView} onPress = {() => {that. _ cityNameClick (cityJson) }}> <View style = {styles. rowdata }> <Text style = {styles. rowdatatext >{cityjson. name} </Text> </View> </TouchableOpacity>)} _ renderListSectionHeader (sectionData, sectionID) {return (<View style = {styles. sectionView }> <Text style = {styles. sectionText >{sectiondata }</Text> </View>);} render () {return (<View style = {styles. container }> <View style = {styles. listContainner }> <ListView ref = {listView => this. _ listView = listView} contentContainerStyle = {styles. contentContainer} dataSource = {this. state. dataSource} renderRow = {this. _ renderListRow} renderSectionHeader = {this. _ renderListSectionHeader} enableEmptySections = {true} initialListSize = {500}/> <View style = {styles. letters >{this. state. letters. map (letter, index) => this. _ renderRightLetters (letter, index ))} </View> <Toast ref = "toast" position = 'top' positionValue = {200} fadeInDuration = {750} fadeOutDuration = {1000} opacity = {0.8} /> </View> )}} const styles = StyleSheet. create ({container: {// paddingTop: 50, flex: 1, flexDirection: 'column', backgroundColor: '# F4F4F4',}, listContainner: {height: Dimensions. get ('window '). height, marginBottom: 10}, contentContainer: {flexDirection: 'row', width: width, backgroundColor: 'white', justifyContent: 'flex-start', flexWrap: 'wrapp'}, letters: {position: 'absolute ', height: height, top: 0, bottom: 0, right: 10, backgroundColor: 'transparent', // justifyContent: 'flex-start', // alignItems: 'flex-start' alignItems: 'center', justifyContent: 'center'}, letter: {height: height * 4/100, width: width * 4/50, justifyContent: 'center', alignItems: 'center'}, letterText: {textAlign: 'center', fontSize: height * 1.1/50, color: '# e75404'}, sectionView: {paddingTop: 5, paddingBottom: 5, height: 30, paddingLeft: 10, width: width, backgroundColor:' # F4F4F4 '}, sectionText: {color: '# e75404', fontWeight: 'bold '}, rowView: {height: ROWHEIGHT, paddingLeft: 10, paddingRight: 10, borderBottomColor:' # F4F4F4 ', borderBottomWidth: 0.5}, rowdata: {paddingTop: 10, paddingBottom: 2}, rowdatatext: {color: 'Gray ', width: width}, rowViewBox: {height: ROWHEIGHT_BOX, width: (width-30)/3, flexDirection: 'row', backgroundColor: '# ffff'}, rowdataBox: {borderWidth: 1, borderColor:' # dbdbdbdb', marginTop: 5, marginBottom: 5, paddingBottom: 2, marginLeft: 10, marginRight: 10, flex: 1, justifyContent: 'center', alignItems: 'center'}, rowDataTextBox: {marginTop: 5, flex: 1, height: 20 }});

Then you need to implement a search box in the header.

SearchBox. js

'Use strict '; import React, {Component} from 'react'; import {View, TextInput, StyleSheet, Platform,} from 'react-native '; export default class SearchBox extends Component {constructor (props) {super (props); this. state = {value: ''};} onEndEditingKeyword (vv) {console. log (vv);} onChanegeTextKeyword (vv) {console. log ('onchanegetextkeyword', vv); this. setState ({value: vv}); this. props. onChanegeTex TKeyword (vv);} render () {return (<View style = {styles. container }> <View style = {styles. inputBox }> <View style = {styles. inputIcon }></View> <TextInput ref = "keyword" autoCapitalize = "none" value = {this. props. keyword} onChangeText = {this. onChanegeTextKeyword. bind (this)} returnKeyType = "search" maxLength = {20} style = {styles. inputText} underlineColorAndroid = "transparent" placeholder = {'Enter the city name or pinyin query'}/> </View> </View>) }} const styles = StyleSheet. create ({container: {marginTop: 5, marginBottom: 5, backgroundColor: '# ffff', flexDirection: 'row', height: Platform. OS = 'ios '? 35: 45, borderBottomWidth: StyleSheet. hairlineWidth, borderBottomColor: '# cdcdcd', paddingBottom: 5}, inputBox: {height: Platform. OS === 'ios '? 30: 40, marginLeft: 5, marginRight: 5, flex: 1, flexDirection: 'row', backgroundColor: '# E6E7E8'}, inputIcon: {margin: Platform. OS = 'ios '? 5: 10}, inputText: {alignSelf: 'flex-end', marginTop: Platform. OS = 'ios '? 0: 0, flex: 1, height: Platform. OS = 'ios '? 30: 40, marginLeft: 2, marginRight: 5, fontSize: 12, lineHeight: 30, textAlignVertical: 'bottom ', textDecorationLine: 'none '}});

Final effect:

 

 

The last step is to draw the interface. You can download the source code to view it. Source Code address: react-native-city_jb51.rar

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.