最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

自己動(dòng)手封裝一個(gè)React Native多級(jí)聯(lián)動(dòng)

 更新時(shí)間:2018年09月19日 11:19:52   作者:zhaowenyin  
這篇文章主要介紹了自己動(dòng)手封裝一個(gè)React Native多級(jí)聯(lián)動(dòng),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

背景

肯定是最近有一個(gè)項(xiàng)目,需要一個(gè)二級(jí)聯(lián)動(dòng)功能了!

本來想封裝完整之后,放在github上面賺星星,但發(fā)現(xiàn)市面上已經(jīng)有比較成熟的了,為什么我在開發(fā)之前沒去搜索一下(項(xiàng)目很趕進(jìn)度),淚崩啊,既然已經(jīng)封裝就來說說過程吧

任務(wù)開始

一. 原型圖或設(shè)計(jì)圖

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

ReactNative多級(jí)聯(lián)動(dòng)

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

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

1. 這個(gè)組件需要達(dá)到的功能是什么?

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

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], // 指定選擇每一級(jí)的第幾項(xiàng),可以不填不傳,默認(rèn)為0(第一項(xiàng))
   visible: true, // 
   options: [ // 選項(xiàng)數(shù)據(jù),label為顯示的名稱,children為下一級(jí),按需加載直接改變options的值就行了
    {
     label: 'A',
     children: [
      {
       label: 'J'
      },
      {
       label: 'K'
      }
     ]
    },
    {
     label: 'B',
     children: [
      {
       label: 'X'
      },
      {
       label: 'Y'
      }
     ]
    }
   ]
  }
 }
 onChange(arr) { // 選中項(xiàng)改變時(shí)觸發(fā), arr為當(dāng)前每一級(jí)選中項(xiàng)索引,如選中B和Y,此時(shí)的arr就等于[1,1]
  console.log(arr)
 }
 onOk(arr) { // 最終確認(rèn)時(shí)觸發(fā),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在前期,往往會(huì)在封裝的過程中,增加會(huì)修改,根據(jù)實(shí)際情況靈活變通

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

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

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, // 選項(xiàng)數(shù)據(jù)
   indexs: props.defaultIndexs || [] // 當(dāng)前選擇的是每一級(jí)的每一項(xiàng),如[1, 0],第一級(jí)的第2項(xiàng),第二級(jí)的第一項(xiàng)
  }
  this.close = this.close.bind(this) // 指定this
  this.ok = this.ok.bind(this) // 指定this
 }
 close () { // 取消按鈕事件
  this.props.onClose && this.props.onClose()
 }

 ok () { // 確認(rèn)按鈕事件
  this.props.onOk && this.props.onOk(this.state.indexs)
 }
 onChange () { // 選項(xiàng)變化的回調(diào)函數(shù)

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

 }

 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}>確認(rèn)</Text>
       </TouchableOpacity>
      </View>
     </TouchableOpacity>
    </TouchableOpacity>
   </View>
  )
 }
}

選擇項(xiàng)組的拼裝是核心功能,單獨(dú)提出一個(gè)函數(shù)(renderItems)來,方便管理和后期維護(hù)

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

PickerItem為單個(gè)選擇項(xiàng)組件,react native中的自帶Picker在安卓和IOS上面表現(xiàn)的樣式是不一樣的,如果產(chǎn)品要求一樣的話,就在PickerItem里面改,只需提供相同的接口,相當(dāng)于PickerItem是獨(dú)立的,維護(hù)起來很方便

// 單個(gè)選項(xiàng)
class PickerItem extends Component {
 static propTypes = {
  list: PropTypes.array,
  onChange: PropTypes.func,
  defaultIndex: PropTypes.number,
 }

 static getDerivedStateFromProps(nextProps, prevState) { // list選項(xiàng)列表和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的回調(diào)函數(shù)onChange

 onChange (itemIndex, currentIndex) { // itemIndex選中的是第幾項(xiàng),currentIndex第幾級(jí)發(fā)生了變化
  const indexArr = []
  const { options = [], indexs = [] } = this.state
  const re = (arr, index) => { // index為第幾層,循環(huán)每一級(jí)
   if (arr && arr.length > 0) {
    let childIndex
    if (index < currentIndex) { // 當(dāng)前級(jí)小于發(fā)生變化的層級(jí), 選中項(xiàng)還是之前的項(xiàng)
     childIndex = indexs[index] || 0
    } else if (index === currentIndex) { // 當(dāng)前級(jí)等于發(fā)生變化的層級(jí), 選中項(xiàng)是傳來的itemIndex
     childIndex = itemIndex
    } else { // 當(dāng)前級(jí)大于發(fā)生變化的層級(jí), 選中項(xiàng)應(yīng)該置為默認(rèn)0,因?yàn)橄录?jí)的選項(xiàng)會(huì)隨著上級(jí)的變化而變化
     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 // 重置所有選中項(xiàng),重新渲染
   },
   () => {
    this.props.onChange && this.props.onChange(indexArr)
   }
  )
 }

總結(jié)

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

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

完整代碼

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

// 單個(gè)選項(xiàng)
class PickerItem extends Component {
 static propTypes = {
  list: PropTypes.array,
  onChange: PropTypes.func,
  defaultIndex: PropTypes.number,
 }

 static getDerivedStateFromProps(nextProps, prevState) { // list選項(xiàng)列表和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數(shù)據(jù)選項(xiàng)或指定項(xiàng)變化時(shí)重新渲染
  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, // 選項(xiàng)數(shù)據(jù)
   indexs: props.defaultIndexs || [] // 當(dāng)前選擇的是每一級(jí)的每一項(xiàng),如[1, 0],第一級(jí)的第2項(xiàng),第二級(jí)的第一項(xiàng)
  }
  this.close = this.close.bind(this) // 指定this
  this.ok = this.ok.bind(this) // 指定this
 }
 close () { // 取消按鈕事件
  this.props.onClose && this.props.onClose()
 }

 ok () { // 確認(rèn)按鈕事件
  this.props.onOk && this.props.onOk(this.state.indexs)
 }
 onChange (itemIndex, currentIndex) { // itemIndex選中的是第幾項(xiàng),currentIndex第幾級(jí)發(fā)生了變化
  const indexArr = []
  const { options = [], indexs = [] } = this.state
  const re = (arr, index) => { // index為第幾層,循環(huán)每一級(jí)
   if (arr && arr.length > 0) {
    let childIndex
    if (index < currentIndex) { // 當(dāng)前級(jí)小于發(fā)生變化的層級(jí), 選中項(xiàng)還是之前的項(xiàng)
     childIndex = indexs[index] || 0
    } else if (index === currentIndex) { // 當(dāng)前級(jí)等于發(fā)生變化的層級(jí), 選中項(xiàng)是傳來的itemIndex
     childIndex = itemIndex
    } else { // 當(dāng)前級(jí)大于發(fā)生變化的層級(jí), 選中項(xiàng)應(yīng)該置為默認(rèn)0,因?yàn)橄录?jí)的選項(xiàng)會(huì)隨著上級(jí)的變化而變化
     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 // 重置所有選中項(xiàng),重新渲染
   },
   () => {
    this.props.onChange && this.props.onChange(indexArr)
   }
  )
 }
 renderItems () { // 拼裝選擇項(xiàng)組
  const items = []
  const { options = [], indexs = [] } = this.state
  const re = (arr, index) => { // index為第幾級(jí)
   if (arr && arr.length > 0) {
    const childIndex = indexs[index] || 0 // 當(dāng)前級(jí)指定選中第幾項(xiàng),默認(rèn)為第一項(xiàng)
    items.push({
     defaultIndex: childIndex,
     values: arr //當(dāng)前級(jí)的選項(xiàng)列表
    })
    if (arr[childIndex] && arr[childIndex].children) {
     const nextIndex = index + 1
     re(arr[childIndex].children, nextIndex)
    }
   }
  }
  re(options, 0) // re為一個(gè)遞歸函數(shù)
  return items.map((obj, index) => {
   return ( // PickerItem為單個(gè)選擇項(xiàng),list為選項(xiàng)列表,defaultIndex為指定選擇第幾項(xiàng),onChange選中選項(xiàng)改變時(shí)回調(diào)函數(shù)
    <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}>確認(rèn)</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

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • react+antd 遞歸實(shí)現(xiàn)樹狀目錄操作

    react+antd 遞歸實(shí)現(xiàn)樹狀目錄操作

    這篇文章主要介紹了react+antd 遞歸實(shí)現(xiàn)樹狀目錄操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • React state狀態(tài)屬性詳細(xì)講解

    React state狀態(tài)屬性詳細(xì)講解

    React將組件(component)看成一個(gè)狀態(tài)機(jī)(State Machines),通過其內(nèi)部自定義的狀態(tài)(State)和生命周期(Lifecycle)實(shí)現(xiàn)并與用戶交互,維持組件的不同狀態(tài)
    2022-09-09
  • react-native 封裝視頻播放器react-native-video的使用

    react-native 封裝視頻播放器react-native-video的使用

    本文主要介紹了react-native 封裝視頻播放器react-native-video的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-01-01
  • React實(shí)現(xiàn)表格選取

    React實(shí)現(xiàn)表格選取

    這篇文章主要為大家詳細(xì)介紹了React實(shí)現(xiàn)表格選取,類似于Excel選中一片區(qū)域并獲得選中區(qū)域的所有數(shù)據(jù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • React詳細(xì)講解JSX和組件的使用

    React詳細(xì)講解JSX和組件的使用

    jsx就是javsscript與xml結(jié)合的一種格式,是js語法的一種擴(kuò)展,只要把html代碼寫在js中就是jsx。react中定義組件有3種寫法:函數(shù)的方式、es5的寫法、es6(類)的寫法
    2022-08-08
  • React日期時(shí)間顯示組件的封裝方法

    React日期時(shí)間顯示組件的封裝方法

    這篇文章主要為大家詳細(xì)介紹了React日期時(shí)間顯示組件的封裝方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • React Hook 監(jiān)聽localStorage更新問題

    React Hook 監(jiān)聽localStorage更新問題

    這篇文章主要介紹了React Hook 監(jiān)聽localStorage更新問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • React.memo函數(shù)中的參數(shù)示例詳解

    React.memo函數(shù)中的參數(shù)示例詳解

    這篇文章主要為大家介紹了React.memo函數(shù)中的參數(shù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-09-09
  • React狀態(tài)提升案例介紹

    React狀態(tài)提升案例介紹

    這篇文章主要介紹了React狀態(tài)提升案例,所謂 狀態(tài)提升 就是將各個(gè)子組件的 公共state 提升到它們的父組件進(jìn)行統(tǒng)一存儲(chǔ)、處理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧
    2023-04-04
  • React實(shí)現(xiàn)一個(gè)拖拽排序組件的示例代碼

    React實(shí)現(xiàn)一個(gè)拖拽排序組件的示例代碼

    這篇文章主要給大家介紹了React實(shí)現(xiàn)一個(gè)拖拽排序組件?-?支持多行多列、支持TypeScript、支持Flip動(dòng)畫、可自定義拖拽區(qū)域,文章通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下
    2023-11-11

最新評(píng)論

桑植县| 上饶县| 永吉县| 虎林市| 新化县| 巴林左旗| 阿勒泰市| 澄迈县| 临城县| 大冶市| 井冈山市| 郁南县| 雷波县| 白水县| 青浦区| 渭南市| 承德市| 昭苏县| 武定县| 龙门县| 洮南市| 宝山区| 晋州市| 翁牛特旗| 城固县| 鄢陵县| 西畴县| 永济市| 龙川县| 临潭县| 泗洪县| 高平市| 阜城县| 积石山| 会昌县| 当雄县| 定结县| 密山市| 尚志市| 普宁市| 梁河县|