動手封裝一個React Native多級聯動

背景

確定是最近有一個項目,須要一個二級聯動功能了!
原本想封裝完整以後,放在github上面賺星星,但發現市面上已經有比較成熟的了,爲何我在開發以前沒去搜索一下(項目很趕進度),淚崩啊,既然已經封裝就來講說過程吧react

任務開始

一. 原型圖或設計圖

在封裝一個組件以前,首先你要知道組件長什麼樣子,大概的輪廓要了解
圖片描述git

二. 構思結構

在封裝以前,先在腦海裏面想一下github

1. 這個組件須要達到的功能是什麼?react-native

改變一級後,二級會跟着變化,改變二級,三級會變,以此類推,能夠指定須要選中的項,能夠動態改變每一級的值,支持按需加載數據結構

2. 暴露出來的API是什麼?函數

// 已封裝的組件(Pickers.js)
import React, { Component } from 'react'
import Pickers from './Pickers'

class Screen extends Component {
  constructor (props) {
    super(props)
    this.state = {
      defaultIndexs: [1, 0], // 指定選擇每一級的第幾項,能夠不填不傳,默認爲0(第一項)
      visible: true,  // 
      options: [ // 選項數據,label爲顯示的名稱,children爲下一級,按需加載直接改變options的值就好了
        {
          label: 'A',
          children: [
            {
              label: 'J'
            },
            {
              label: 'K'
            }
          ]
        },
        {
          label: 'B',
          children: [
            {
              label: 'X'
            },
            {
              label: 'Y'
            }
          ]
        }
      ]
    }
  }
  onChange(arr) { // 選中項改變時觸發, arr爲當前每一級選中項索引,如選中B和Y,此時的arr就等於[1,1]
    console.log(arr)
  }
  onOk(arr) { // 最終確認時觸發,arr同上
    console.log(arr)
  }
  render() {
    return (
      <View style={styles.container}>
        <Pickers
          options={this.state.options}
          defaultIndexs={this.state.defaultIndexs}
          onChange={this.onChange.bind(this)}
          onOk={this.onOk.bind(this)}>
        </Pickers>
      </View>
    )
  }
}

API在前期,每每會在封裝的過程當中,增長會修改,根據實際狀況靈活變通 flex

3. 如何讓使用者使用起來更方便?this

用目前比較流行的數據結構和風格(能夠借鑑其它組件),接口名稱定義一目瞭然spa

4. 如何能適應更多的場景?設計

只封裝功能,不封裝業務

三. 開始寫代碼

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
} from 'react-native'

class Pickers extends Component {
  static propTypes = {
    options: PropTypes.array,
    defaultIndexs: PropTypes.array,
    onClose: PropTypes.func,
    onChange: PropTypes.func,
    onOk: PropTypes.func,
  }

  constructor (props) {
    super(props)
    this.state = {
      options: props.options, // 選項數據
      indexs: props.defaultIndexs || [] // 當前選擇的是每一級的每一項,如[1, 0],第一級的第2項,第二級的第一項
    }
    this.close = this.close.bind(this) // 指定this
    this.ok = this.ok.bind(this) // 指定this
  }
  close () { // 取消按鈕事件
    this.props.onClose && this.props.onClose()
  }

  ok () { // 確認按鈕事件
    this.props.onOk && this.props.onOk(this.state.indexs)
  }
  onChange () { // 選項變化的回調函數

  }
  renderItems () { // 拼裝選擇項組

  }

  render() {
    return (
      <View
        style={styles.box}>
        <TouchableOpacity
          onPress={this.close}
          style={styles.bg}>
          <TouchableOpacity
            activeOpacity={1}
            style={styles.dialogBox}>
            <View style={styles.pickerBox}>
              {this.renderItems()}
            </View>
            <View style={styles.btnBox}>
              <TouchableOpacity
                onPress={this.close}
                style={styles.cancelBtn}>
                <Text
                  numberOfLines={1}
                  ellipsizeMode={"tail"}
                  style={styles.cancelBtnText}>取消</Text>
              </TouchableOpacity>
              <TouchableOpacity
                onPress={this.ok}
                style={styles.okBtn}>
                <Text
                  numberOfLines={1}
                  ellipsizeMode={"tail"}
                  style={styles.okBtnText}>確認</Text>
              </TouchableOpacity>
            </View>
          </TouchableOpacity>
        </TouchableOpacity>
      </View>
    )
  }
}

選擇項組的拼裝是核心功能,單獨提出一個函數(renderItems)來,方便管理和後期維護

renderItems () { // 拼裝選擇項組
    const items = []
    const { options = [], indexs = [] } = this.state
    const re = (arr, index) => { // index爲第幾級
      if (arr && arr.length > 0) {
        const childIndex = indexs[index] || 0 // 當前級指定選中第幾項,默認爲第一項
        items.push({
          defaultIndex: childIndex,
          values: arr //當前級的選項列表
        })
        if (arr[childIndex] && arr[childIndex].children) {
          const nextIndex = index + 1
          re(arr[childIndex].children, nextIndex)
        }
      }
    }
    re(options, 0) // re爲一個遞歸函數
    return items.map((obj, index) => {
      return ( // PickerItem爲單個選擇項,list爲選項列表,defaultIndex爲指定選擇第幾項,onChange選中選項改變時回調函數,itemIndex選中的第幾項,index爲第幾級,如(2, 1)爲選中第二級的第三項
        <PickerItem
          key={index.toString()}
          list={obj.values}
          defaultIndex={obj.defaultIndex}
          onChange={(itemIndex) => { this.onChange(itemIndex, index)}}
          />
      )
    })
  }

PickerItem爲單個選擇項組件,react native中的自帶Picker在安卓和IOS上面表現的樣式是不同的,若是產品要求同樣的話,就在PickerItem裏面改,只需提供相同的接口,至關於PickerItem是獨立的,維護起來很方便

// 單個選項
class PickerItem extends Component {
  static propTypes = {
    list: PropTypes.array,
    onChange: PropTypes.func,
    defaultIndex: PropTypes.number,
  }

  static getDerivedStateFromProps(nextProps, prevState) { // list選項列表和defaultIndex變化以後從新渲染
    if (nextProps.list !== prevState.list ||
        nextProps.defaultIndex !== prevState.defaultIndex) {
      return {
        list: nextProps.list,
        index: nextProps.defaultIndex
      }
    }
    return null
  }

  constructor (props) {
    super(props)
    this.state = {
      list: props.list,
      index: props.defaultIndex
    }
    this.onValueChange = this.onValueChange.bind(this)
  }

  onValueChange (itemValue, itemIndex) {
    this.setState( // setState不是當即渲染
      {
        index: itemIndex
      },
      () => {
        this.props.onChange && this.props.onChange(itemIndex)
      })

  }

  render() {
    // Picker的接口直接看react native的文檔https://reactnative.cn/docs/picker/
    const { list = [], index = 0 } = this.state
    const value = list[index]
    const Items = list.map((obj, index) => {
      return <Picker.Item key={index} label={obj.label} value={obj} />
    })
    return (
      <Picker
        selectedValue={value}
        style={{ flex: 1 }}
        mode="dropdown"
        onValueChange={this.onValueChange}>
        {Items}
      </Picker>
    )
  }
}

renderItems()中PickerItem的回調函數onChange

onChange (itemIndex, currentIndex) { // itemIndex選中的是第幾項,currentIndex第幾級發生了變化
    const indexArr = []
    const { options = [], indexs = [] } = this.state
    const re = (arr, index) => { // index爲第幾層,循環每一級
      if (arr && arr.length > 0) {
        let childIndex
        if (index < currentIndex) { // 當前級小於發生變化的層級, 選中項仍是以前的項
          childIndex = indexs[index] || 0
        } else if (index === currentIndex) { // 當前級等於發生變化的層級, 選中項是傳來的itemIndex
          childIndex = itemIndex
        } else { // 當前級大於發生變化的層級, 選中項應該置爲默認0,由於下級的選項會隨着上級的變化而變化
          childIndex = 0
        }
        indexArr[index] = childIndex
        if (arr[childIndex] && arr[childIndex].children) {
          const nextIndex = index + 1
          re(arr[childIndex].children, nextIndex)
        }
      }
    }
    re(options, 0)
    this.setState(
      {
        indexs: indexArr // 重置全部選中項,從新渲染
      },
      () => {
        this.props.onChange && this.props.onChange(indexArr)
      }
    )
  }

總結

市面上成熟的多級聯動不少,若是對功能要求比較高的話,建議用成熟的組件,這樣開發成本低,文檔全,團隊中其餘人易接手。若是隻有用到裏面很是簡單的功能,很快就能夠開發好,建議本身開發,不必引用一個龐大的包,若是要特殊定製的話,就只有本身開發。不管以上哪一種狀況,能理解裏面的運行原理甚好

主要說明在代碼裏面,也能夠直接拷貝完整代碼看,沒多少內容,若是須要獲取對應值的話,直接經過獲取的索引查對應值就好了

完整代碼

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
  StyleSheet,
  View,
  Text,
  Picker,
  TouchableOpacity,
} from 'react-native'

// 單個選項
class PickerItem extends Component {
  static propTypes = {
    list: PropTypes.array,
    onChange: PropTypes.func,
    defaultIndex: PropTypes.number,
  }

  static getDerivedStateFromProps(nextProps, prevState) { // list選項列表和defaultIndex變化以後從新渲染
    if (nextProps.list !== prevState.list ||
        nextProps.defaultIndex !== prevState.defaultIndex) {
      return {
        list: nextProps.list,
        index: nextProps.defaultIndex
      }
    }
    return null
  }

  constructor (props) {
    super(props)
    this.state = {
      list: props.list,
      index: props.defaultIndex
    }
    this.onValueChange = this.onValueChange.bind(this)
  }

  onValueChange (itemValue, itemIndex) {
    this.setState( // setState不是當即渲染
      {
        index: itemIndex
      },
      () => {
        this.props.onChange && this.props.onChange(itemIndex)
      })

  }

  render() {
    // Picker的接口直接看react native的文檔https://reactnative.cn/docs/picker/
    const { list = [], index = 0 } = this.state
    const value = list[index]
    const Items = list.map((obj, index) => {
      return <Picker.Item key={index} label={obj.label} value={obj} />
    })
    return (
      <Picker
        selectedValue={value}
        style={{ flex: 1 }}
        mode="dropdown"
        onValueChange={this.onValueChange}>
        {Items}
      </Picker>
    )
  }
}

// Modal 安卓上沒法返回
class Pickers extends Component {
  static propTypes = {
    options: PropTypes.array,
    defaultIndexs: PropTypes.array,
    onClose: PropTypes.func,
    onChange: PropTypes.func,
    onOk: PropTypes.func,
  }
  static getDerivedStateFromProps(nextProps, prevState) { // options數據選項或指定項變化時從新渲染
    if (nextProps.options !== prevState.options ||
        nextProps.defaultIndexs !== prevState.defaultIndexs) {
      return {
        options: nextProps.options,
        indexs: nextProps.defaultIndexs
      }
    }
    return null
  }
  constructor (props) {
    super(props)
    this.state = {
      options: props.options, // 選項數據
      indexs: props.defaultIndexs || [] // 當前選擇的是每一級的每一項,如[1, 0],第一級的第2項,第二級的第一項
    }
    this.close = this.close.bind(this) // 指定this
    this.ok = this.ok.bind(this) // 指定this
  }
  close () { // 取消按鈕事件
    this.props.onClose && this.props.onClose()
  }

  ok () { // 確認按鈕事件
    this.props.onOk && this.props.onOk(this.state.indexs)
  }
  onChange (itemIndex, currentIndex) { // itemIndex選中的是第幾項,currentIndex第幾級發生了變化
    const indexArr = []
    const { options = [], indexs = [] } = this.state
    const re = (arr, index) => { // index爲第幾層,循環每一級
      if (arr && arr.length > 0) {
        let childIndex
        if (index < currentIndex) { // 當前級小於發生變化的層級, 選中項仍是以前的項
          childIndex = indexs[index] || 0
        } else if (index === currentIndex) { // 當前級等於發生變化的層級, 選中項是傳來的itemIndex
          childIndex = itemIndex
        } else { // 當前級大於發生變化的層級, 選中項應該置爲默認0,由於下級的選項會隨着上級的變化而變化
          childIndex = 0
        }
        indexArr[index] = childIndex
        if (arr[childIndex] && arr[childIndex].children) {
          const nextIndex = index + 1
          re(arr[childIndex].children, nextIndex)
        }
      }
    }
    re(options, 0)
    this.setState(
      {
        indexs: indexArr // 重置全部選中項,從新渲染
      },
      () => {
        this.props.onChange && this.props.onChange(indexArr)
      }
    )
  }
  renderItems () { // 拼裝選擇項組
    const items = []
    const { options = [], indexs = [] } = this.state
    const re = (arr, index) => { // index爲第幾級
      if (arr && arr.length > 0) {
        const childIndex = indexs[index] || 0 // 當前級指定選中第幾項,默認爲第一項
        items.push({
          defaultIndex: childIndex,
          values: arr //當前級的選項列表
        })
        if (arr[childIndex] && arr[childIndex].children) {
          const nextIndex = index + 1
          re(arr[childIndex].children, nextIndex)
        }
      }
    }
    re(options, 0) // re爲一個遞歸函數
    return items.map((obj, index) => {
      return ( // PickerItem爲單個選擇項,list爲選項列表,defaultIndex爲指定選擇第幾項,onChange選中選項改變時回調函數
        <PickerItem
          key={index.toString()}
          list={obj.values}
          defaultIndex={obj.defaultIndex}
          onChange={(itemIndex) => { this.onChange(itemIndex, index)}}
          />
      )
    })
  }

  render() {
    return (
      <View
        style={styles.box}>
        <TouchableOpacity
          onPress={this.close}
          style={styles.bg}>
          <TouchableOpacity
            activeOpacity={1}
            style={styles.dialogBox}>
            <View style={styles.pickerBox}>
              {this.renderItems()}
            </View>
            <View style={styles.btnBox}>
              <TouchableOpacity
                onPress={this.close}
                style={styles.cancelBtn}>
                <Text
                  numberOfLines={1}
                  ellipsizeMode={"tail"}
                  style={styles.cancelBtnText}>取消</Text>
              </TouchableOpacity>
              <TouchableOpacity
                onPress={this.ok}
                style={styles.okBtn}>
                <Text
                  numberOfLines={1}
                  ellipsizeMode={"tail"}
                  style={styles.okBtnText}>確認</Text>
              </TouchableOpacity>
            </View>
          </TouchableOpacity>
        </TouchableOpacity>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  box: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    zIndex: 9999,
  },
  bg: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.4)',
    justifyContent: 'center',
    alignItems: 'center'
  },
  dialogBox: {
    width: 260,
    flexDirection: "column",
    backgroundColor: '#fff',
  },
  pickerBox: {
    flexDirection: "row",
  },
  btnBox: {
    flexDirection: "row",
    height: 45,
  },
  cancelBtn: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    borderColor: '#4A90E2',
    borderWidth: 1,
  },
  cancelBtnText: {
    fontSize: 15,
    color: '#4A90E2'
  },
  okBtn: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#4A90E2',
  },
  okBtnText: {
    fontSize: 15,
    color: '#fff'
  },
})

export default Pickers
相關文章
相關標籤/搜索