陈桥驿站 陈桥驿站

ReactNative 三级联动选择框

--> React Native 阅读 ( 376 ) 文章转载请注明来源!

前言

详解Picker三级联动数据准备和使用。

代码

MySQL设计

Java

SubjectDao.java

package cn.tomcat7.scholar.dao;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

import cn.tomcat7.scholar.HibernateSessionFactory;
import cn.tomcat7.scholar.bean.Subject;

/**
 * A data access object (DAO) providing persistence and search support for
 * Subject entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see cn.tomcat7.scholar.bean.Subject
 * @author MyEclipse Persistence Tools
 */
public class SubjectDAO extends BaseHibernateDAO {
    // property constants
    public static final String NAME = "name";
    public static final String PARENT = "parent";

    @SuppressWarnings("unchecked")
    public List<Subject> findAll() {
        List<Subject> subjects = new ArrayList<Subject>();
        try {
            Session session = HibernateSessionFactory.getSession();
            session.beginTransaction();
            String queryString = "from Subject";
            Query queryObject = getSession().createQuery(queryString);
            subjects = queryObject.list();
            session.getTransaction().commit();
        } catch (RuntimeException re) {
            re.printStackTrace();
        }
        return subjects;
    }
    public Subject merge(Subject detachedInstance) {
        Subject subject = null;
        try {
            Session session = HibernateSessionFactory.getSession();
            session.beginTransaction();
            subject = (Subject) getSession().merge(detachedInstance);
            session.getTransaction().commit();
        } catch (RuntimeException re) {
            re.printStackTrace();
        }
        return subject;
    }
}

Subject.java

package cn.tomcat7.scholar.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Subject entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "subject", catalog = "Qiukui")

public class Subject implements java.io.Serializable {

    // Fields
    private static final long serialVersionUID = 7692165190318137247L;
    private Integer id;
    private String name;
    private Integer parent;

    // Constructors

    /** default constructor */
    public Subject() {
    }

    /** full constructor */
    public Subject(String name, Integer parent) {
        this.name = name;
        this.parent = parent;
    }

    // Property accessors
    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = "id", unique = true, nullable = false)

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name = "name", length = 1024)

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "parent")

    public Integer getParent() {
        return this.parent;
    }

    public void setParent(Integer parent) {
        this.parent = parent;
    }

    @Override
    public String toString() {
        return "Subject [id=" + id + ", name=" + name + ", parent=" + parent + "]";
    }
}

PickerUtils.java

package cn.tomcat7.scholar.tools;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.GsonBuilder;

import cn.tomcat7.scholar.bean.Subject;
import cn.tomcat7.scholar.dao.SubjectDAO;

public class PickerUtils {
    public static void main(String[] args) {
        List<Subject> subjects = new SubjectDAO().findAll();
//        System.out.println(subjects.size());
        ArrayList<One> list = new ArrayList<One>();
//        System.out.println(children(subjects, 50));
        for(Subject s : subjects) {
            if(s.getParent() == 0) {
                //第一层
                String oneName = s.getName();
                ArrayList<Two> city = new ArrayList<Two>();
                //第二层
//                System.out.println(s.getId());
                for(Subject sun : children(subjects, s.getId())) {
                    //第三层
//                    System.out.println(sun.getName());
                    ArrayList<String> areas = new ArrayList<String>();
                    if(children(subjects, sun.getId()).size() == 0) {
                        System.out.println(sun.getName());
                        new SubjectDAO().merge(new Subject(sun.getName(), sun.getId()));
                    }
                    else {
                        for(Subject child : children(subjects, sun.getId())) {
                            areas.add(child.getName());
                        }
                        city.add(new Two(sun.getName(), areas));
                    }
                }
                list.add(new One(oneName, city));
            }
        }
        System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(list));
    }
    
    private static ArrayList<Subject> children(List<Subject> list, int parent)  {
        ArrayList<Subject> subjects = new ArrayList<Subject>();
        for(Subject s : list) {
            if(s.getParent() == parent) {
                subjects.add(s);
            }
        }
        return subjects;
    }
}

class One {
    private String name;
    private ArrayList<Two> city;
    public One(String name, ArrayList<Two> city) {
        super();
        this.name = name;
        this.city = city;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public ArrayList<Two> getCity() {
        return city;
    }
    public void setCity(ArrayList<Two> city) {
        this.city = city;
    }
}

class Two {
    private String name;
    private ArrayList<String> area;
    public Two(String name, ArrayList<String> area) {
        super();
        this.name = name;
        this.area = area;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public ArrayList<String> getArea() {
        return area;
    }
    public void setArea(ArrayList<String> area) {
        this.area = area;
    }
}

ReactNative Picker

import Picker from 'react-native-picker';
import area from '../datas/triple.json';
createAreaData() {
  let data = [];
  let len = area.length;
  for(let i=0;i<len;i++){
      let city = [];
      for(let j=0,cityLen=area[i]['city'].length;j<cityLen;j++){
          let _city = {};
          _city[area[i]['city'][j]['name']] = area[i]['city'][j]['area'];
          city.push(_city);
      }

      let _data = {};
      _data[area[i]['name']] = city;
      data.push(_data);
  }
  return data;
}
<TouchableOpacity
  style={{marginRight: 8, flexDirection: 'row', alignItems: 'center'}}
  onPress={()=>{
    Picker.init({
      pickerData: that.createAreaData(),
      selectedValue: ['建筑工程', '一级消防工程师', '消防安全技术综合能力'],
      onPickerConfirm: (item)=>{
        //console.log(item);
        //console.log('onPress itemPosition = ' + position);
        that.setState({
          subjectString: item[2]
        })
      }
    });
    Picker.show();
  }}
  >
  <Text style={{fontSize: 20, color: 'black'}}>{this.state.subjectString}</Text>
  <Image source={require('../images/icon_down_black.png')} style={{width: 8, height: 4}} />
</TouchableOpacity>

本文基于《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权
文章链接:http://www.cctv3.net/archives/rnTriplePicker.html (转载时请注明本文出处及文章链接)

React Native
发表新评论
雷姆
拉姆