ホームページ  >  記事  >  ウェブフロントエンド  >  React Native のマルチレベルリンケージをカプセル化する方法 (コード実装)

React Native のマルチレベルリンケージをカプセル化する方法 (コード実装)

不言
不言オリジナル
2018-09-19 16:55:261863ブラウズ

この記事の内容は、React Native のマルチレベル連携のカプセル化 (コード実装) に関するものです。必要な方は参考にしていただければ幸いです。

背景

最近、二次連携機能が必要なプロジェクトがあるはずです!
元々は完全にパッケージ化して github に上げてスターを獲得しようと思っていましたが、すでに比較的完成度の高いものが市場にあることがわかりました。なぜ開発前に検索しなかったのでしょう (プロジェクトが急いでいたため)。 )、パッケージ化されたので、私は泣き出しました。プロセスについて話しましょう

タスクが始まります

1. コンポーネントをカプセル化する前に、まずコンポーネントがどのようなものかを大まかに把握する必要があります。概要を理解する必要があります

React Native のマルチレベルリンケージをカプセル化する方法 (コード実装)## 2. 構造を理解する

#Beforeカプセル化しているので、頭の中で考えてください。

1. このコンポーネントが達成する必要がある機能は何ですか?

最初のレベルを変更すると、それに応じて 2 番目のレベルも変更され、2 番目のレベルも変更され、3 番目のレベルも変更されます。というように、選択する必要がある項目を指定できます。各レベルの値を動的に変更できます。オンデマンドでロードをサポートします。

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。さらに多くのシナリオへ?

ビジネスではなく関数のみをカプセル化します

3. コードの作成を開始します

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 は単一の選択コンポーネントです。反応ネイティブの組み込みピッカーは、Android と 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。