成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

動手封裝一個React Native多級聯(lián)動

Coly / 1631人閱讀

摘要:如果只有用到里面非常簡單的功能,很快就可以開發(fā)好,建議自己開發(fā),沒必要引用一個龐大的包,如果要特殊定制的話,就只有自己開發(fā)。

背景

肯定是最近有一個項目,需要一個二級聯(lián)動功能了!
本來想封裝完整之后,放在github上面賺星星,但發(fā)現(xiàn)市面上已經(jīng)有比較成熟的了,為什么我在開發(fā)之前沒去搜索一下(項目很趕進度),淚崩啊,既然已經(jīng)封裝就來說說過程吧

任務(wù)開始 一. 原型圖或設(shè)計圖

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

二. 構(gòu)思結(jié)構(gòu)

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

1. 這個組件需要達到的功能是什么?

改變一級后,二級會跟著變化,改變二級,三級會變,以此類推,可以指定需要選中的項,可以動態(tài)改變每一級的值,支持按需加載

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: [ // 選項數(shù)據(jù),label為顯示的名稱,children為下一級,按需加載直接改變options的值就行了
        {
          label: "A",
          children: [
            {
              label: "J"
            },
            {
              label: "K"
            }
          ]
        },
        {
          label: "B",
          children: [
            {
              label: "X"
            },
            {
              label: "Y"
            }
          ]
        }
      ]
    }
  }
  onChange(arr) { // 選中項改變時觸發(fā), arr為當前每一級選中項索引,如選中B和Y,此時的arr就等于[1,1]
    console.log(arr)
  }
  onOk(arr) { // 最終確認時觸發(fā),arr同上
    console.log(arr)
  }
  render() {
    return (
      
        
        
      
    )
  }
}

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

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

用目前比較流行的數(shù)據(jù)結(jié)構(gòu)和風格(可以借鑒其它組件),接口名稱定義一目了然

4. 如何能適應(yīng)更多的場景?

只封裝功能,不封裝業(yè)務(wù)

三. 開始寫代碼
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, // 選項數(shù)據(jù)
      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 () { // 選項變化的回調(diào)函數(shù)

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

  }

  render() {
    return (
      
        
          
            
              {this.renderItems()}
            
            
              
                取消
              
              
                確認
              
            
          
        
      
    )
  }
}

選擇項組的拼裝是核心功能,多帶帶提出一個函數(shù)(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為一個遞歸函數(shù)
    return items.map((obj, index) => {
      return ( // PickerItem為單個選擇項,list為選項列表,defaultIndex為指定選擇第幾項,onChange選中選項改變時回調(diào)函數(shù),itemIndex選中的第幾項,index為第幾級,如(2, 1)為選中第二級的第三項
         { this.onChange(itemIndex, index)}}
          />
      )
    })
  }

PickerItem為單個選擇項組件,react native中的自帶Picker在安卓和IOS上面表現(xiàn)的樣式是不一樣的,如果產(chǎn)品要求一樣的話,就在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 
    })
    return (
      
        {Items}
      
    )
  }
}

renderItems()中PickerItem的回調(diào)函數(shù)onChange

 onChange (itemIndex, currentIndex) { // itemIndex選中的是第幾項,currentIndex第幾級發(fā)生了變化
    const indexArr = []
    const { options = [], indexs = [] } = this.state
    const re = (arr, index) => { // index為第幾層,循環(huán)每一級
      if (arr && arr.length > 0) {
        let childIndex
        if (index < currentIndex) { // 當前級小于發(fā)生變化的層級, 選中項還是之前的項
          childIndex = indexs[index] || 0
        } else if (index === currentIndex) { // 當前級等于發(fā)生變化的層級, 選中項是傳來的itemIndex
          childIndex = itemIndex
        } else { // 當前級大于發(fā)生變化的層級, 選中項應(yīng)該置為默認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)
      }
    )
  }
總結(jié)

市面上成熟的多級聯(lián)動很多,如果對功能要求比較高的話,建議用成熟的組件,這樣開發(fā)成本低,文檔全,團隊中其他人易接手。如果只有用到里面非常簡單的功能,很快就可以開發(fā)好,建議自己開發(fā),沒必要引用一個龐大的包,如果要特殊定制的話,就只有自己開發(fā)。無論以上哪種情況,能理解里面的運行原理甚好

主要說明在代碼里面,也可以直接拷貝完整代碼看,沒多少內(nèi)容,如果需要獲取對應(yīng)值的話,直接通過獲取的索引查對應(yīng)值就行了

完整代碼
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 
    })
    return (
      
        {Items}
      
    )
  }
}

// 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數(shù)據(jù)選項或指定項變化時重新渲染
    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, // 選項數(shù)據(jù)
      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第幾級發(fā)生了變化
    const indexArr = []
    const { options = [], indexs = [] } = this.state
    const re = (arr, index) => { // index為第幾層,循環(huán)每一級
      if (arr && arr.length > 0) {
        let childIndex
        if (index < currentIndex) { // 當前級小于發(fā)生變化的層級, 選中項還是之前的項
          childIndex = indexs[index] || 0
        } else if (index === currentIndex) { // 當前級等于發(fā)生變化的層級, 選中項是傳來的itemIndex
          childIndex = itemIndex
        } else { // 當前級大于發(fā)生變化的層級, 選中項應(yīng)該置為默認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為一個遞歸函數(shù)
    return items.map((obj, index) => {
      return ( // PickerItem為單個選擇項,list為選項列表,defaultIndex為指定選擇第幾項,onChange選中選項改變時回調(diào)函數(shù)
         { 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

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/97879.html

相關(guān)文章

  • 如何造一個移動端的聯(lián)動選擇器(一)

    摘要:寫在前面之前寫了一篇為移動端而生的自定義多級聯(lián)動選擇器,得到了很多人的關(guān)注。預(yù)知后話地址為移動端而生的自定義多級聯(lián)動選擇器到此,需求已經(jīng)明確。 寫在前面 之前寫了一篇 MultiPicker -『為移動端而生』的自定義多級聯(lián)動選擇器,得到了很多人的關(guān)注。鑒于很多人對這種手寫插件的過程很好奇,所以寫了幾篇文章,來說說它的成長史~ 在閱讀本文之前,確保你有稍微看過 MultiPicker ...

    Steve_Wang_ 評論0 收藏0
  • 如何造一個移動端的聯(lián)動選擇器(一)

    摘要:寫在前面之前寫了一篇為移動端而生的自定義多級聯(lián)動選擇器,得到了很多人的關(guān)注。預(yù)知后話地址為移動端而生的自定義多級聯(lián)動選擇器到此,需求已經(jīng)明確。 寫在前面 之前寫了一篇 MultiPicker -『為移動端而生』的自定義多級聯(lián)動選擇器,得到了很多人的關(guān)注。鑒于很多人對這種手寫插件的過程很好奇,所以寫了幾篇文章,來說說它的成長史~ 在閱讀本文之前,確保你有稍微看過 MultiPicker ...

    andycall 評論0 收藏0
  • 如何造一個移動端的聯(lián)動選擇器(一)

    摘要:寫在前面之前寫了一篇為移動端而生的自定義多級聯(lián)動選擇器,得到了很多人的關(guān)注。預(yù)知后話地址為移動端而生的自定義多級聯(lián)動選擇器到此,需求已經(jīng)明確。 寫在前面 之前寫了一篇 MultiPicker -『為移動端而生』的自定義多級聯(lián)動選擇器,得到了很多人的關(guān)注。鑒于很多人對這種手寫插件的過程很好奇,所以寫了幾篇文章,來說說它的成長史~ 在閱讀本文之前,確保你有稍微看過 MultiPicker ...

    tabalt 評論0 收藏0
  • 如何造一個移動端的聯(lián)動選擇器(三)

    摘要:寫在前面之前寫了一篇為移動端而生的自定義多級聯(lián)動選擇器,得到了很多人的關(guān)注。預(yù)知后話地址為移動端而生的自定義多級聯(lián)動選擇器到此,時間選擇器的核心算法就已經(jīng)基本掌握了。 寫在前面 之前寫了一篇 MultiPicker -『為移動端而生』的自定義多級聯(lián)動選擇器,得到了很多人的關(guān)注。鑒于很多人對這種手寫插件的過程很好奇,所以寫了幾篇文章,來說說它的成長史~ 在閱讀本文之前,確保你有稍微看過 ...

    ls0609 評論0 收藏0
  • 如何造一個移動端的聯(lián)動選擇器(三)

    摘要:寫在前面之前寫了一篇為移動端而生的自定義多級聯(lián)動選擇器,得到了很多人的關(guān)注。預(yù)知后話地址為移動端而生的自定義多級聯(lián)動選擇器到此,時間選擇器的核心算法就已經(jīng)基本掌握了。 寫在前面 之前寫了一篇 MultiPicker -『為移動端而生』的自定義多級聯(lián)動選擇器,得到了很多人的關(guān)注。鑒于很多人對這種手寫插件的過程很好奇,所以寫了幾篇文章,來說說它的成長史~ 在閱讀本文之前,確保你有稍微看過 ...

    zzzmh 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<