首頁  >  文章  >  web前端  >  如何封裝一個React Native多級聯(程式碼實作)

如何封裝一個React Native多級聯(程式碼實作)

不言
不言原創
2018-09-19 16:55:261858瀏覽

這篇文章帶給大家的內容是關於如何封裝一個React Native多級聯(程式碼實現),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

背景

肯定是最近有一個項目,需要一個二級連動功能了!
本來想封裝完整之後,放在github上面賺星星,但發現市面上已經有比較成熟的了,為什麼我在開發之前沒去搜索一下(項目很趕進度),淚崩啊,既然已經封裝就來談談過程吧

任務開始

一.原型圖或設計圖

在封裝一個元件之前,首先你要知道元件長什麼樣子,大概的輪廓要了解

如何封裝一個React Native多級聯(程式碼實作)

二. 構思結構

在封裝之前,先在腦海裡面想一下

1. 這個元件需要達到的功能是什麼?

改變一級後,二級會跟著變化,改變二級,三級會變,以此類推,可以指定需要選取的項,可以動態改變每一級的值,支持按需載入

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>
        <pickers>
        </pickers>
      </view>
    )
  }
}

API在前期,往往會在封裝的過程中,增加會修改,根據實際情況靈活變通

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

用目前比較流行的資料結構和風格(可以藉用其它元件),介面名稱定義一目了然

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>
        <touchableopacity>
          <touchableopacity>
            <view>
              {this.renderItems()}
            </view>
            <view>
              <touchableopacity>
                <text>取消</text>
              </touchableopacity>
              <touchableopacity>
                <text>确认</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> { this.onChange(itemIndex, index)}}
          />
      )
    })
  }</pickeritem>

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></picker.item>
    })
    return (
      <picker>
        {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  {
        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></picker.item>
    })
    return (
      <picker>
        {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  {
        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选中选项改变时回调函数
         { this.onChange(itemIndex, index)}}
          />
      )
    })
  }

  render() {
    return (
      
        
          
            
              {this.renderItems()}
            
            
              
                取消
              
              
                确认
              
            
          
        
      
    )
  }
}

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

以上是如何封裝一個React Native多級聯(程式碼實作)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn