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

React Native可復(fù)用 UI分離布局組件和狀態(tài)組件技巧

 更新時(shí)間:2022年09月07日 16:10:31   作者:todoit  
這篇文章主要為大家介紹了React Native可復(fù)用 UI分離布局組件和狀態(tài)組件使用技巧,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

引言

單選,多選,是很常見的 UI 組件,這里以它們?yōu)槔?,來講解如何分離布局組件和狀態(tài)組件,以實(shí)現(xiàn)較好的復(fù)用性。

假如我們要實(shí)現(xiàn)如下需求:

這類 UI 有如下特點(diǎn):

  • 不管是單選還是多選,都可以有網(wǎng)格布局,我們可以把這個(gè)網(wǎng)格布局單獨(dú)抽離出來,放到一個(gè)獨(dú)立的組件中。
  • 多選有 Label 形式和 CheckBox 形式,表現(xiàn)形式不一樣,但是狀態(tài)邏輯是一樣的,我們可以單獨(dú)封裝這個(gè)狀態(tài)邏輯。
  • 單選有 Label 形式和 RadioButton 形式,表現(xiàn)形式不一樣,但是狀態(tài)邏輯是一樣的,我們可以單獨(dú)封裝這個(gè)狀態(tài)邏輯。
  • 布局可以很復(fù)雜,在某個(gè)層級(jí)中,才會(huì)發(fā)生選擇行為。

現(xiàn)在讓我們一步一步來實(shí)現(xiàn)一個(gè)設(shè)計(jì)良好的,可復(fù)用的 UI 組件。

包裝 Context.Provider 作為父組件

為了實(shí)現(xiàn)父子組件的跨層級(jí)通訊,我們需要使用 React.Context。

首先來實(shí)現(xiàn) CheckGroup 組件。

// CheckContext.ts
export interface Item<T> {
  label: string
  value: T
}
export interface CheckContext<T> {
  checkedItems: Array<Item<T>>
  setCheckedItems: (items: Array<Item<T>>) => void
}
export const CheckContext = React.createContext<CheckContext<any>>({
  checkedItems: [],
  setCheckedItems: () => {},
})

CheckGroup 實(shí)際上是個(gè) CheckContext.Provider。

// CheckGroup.tsx
import { CheckContext, Item } from './CheckContext'
interface CheckGroupProps<T> {
  limit?: number
  checkedItems?: Array<Item<T>>
  onCheckedItemsChanged?: (items: Array<Item<T>>) => void
}
export default function CheckGroup({
  limit = 0,
  checkedItems = [],
  onCheckedItemsChanged,
  children,
}: PropsWithChildren<CheckGroupProps<any>>) {
  const setCheckedItems = (items: Array<Item<any>>) => {
    if (limit <= 0 || items.length <= limit) {
      onCheckedItemsChanged?.(items)
    }
  }
  return (
    <CheckContext.Provider value={{ checkedItems, setCheckedItems }}>
      {children}
    </CheckContext.Provider>
  )
}

使用 Context Hook 來實(shí)現(xiàn)子組件

復(fù)選組件有多種表現(xiàn)形式,我們先來實(shí)現(xiàn) CheckLabel。主要是使用 useContext 這個(gè) hook。

// CheckLabel.tsx
import { CheckContext, Item } from './CheckContext'
interface CheckLabelProps<T> {
  item: Item<T>
  style?: StyleProp<TextStyle>
  checkedStyle?: StyleProp<TextStyle>
}
export default function CheckLabel({
  item,
  style,
  checkedStyle,
}: CheckLabelProps<any>) {
  const { checkedItems, setCheckedItems } = useContext(CheckContext)
  const checked = checkedItems?.includes(item)
  return (
    <Pressable
      onPress={() => {
        if (checked) {
          setCheckedItems(checkedItems.filter((i) => i !== item))
        } else {
          setCheckedItems([...checkedItems, item])
        }
      }}>
      <Text
        style={[
          styles.label,
          style,
          checked ? [styles.checked, checkedStyle] : undefined,
        ]}>
        {item.label}
      </Text>
    </Pressable>
  )
}

現(xiàn)在組合 CheckGroupCheckLabel,看看效果:

可見,復(fù)選功能已經(jīng)實(shí)現(xiàn),但我們需要的是網(wǎng)格布局哦。好的,現(xiàn)在就去寫一個(gè) GridVeiw 來實(shí)現(xiàn)網(wǎng)格布局。

使用 React 頂層 API 動(dòng)態(tài)設(shè)置樣式

我們的 GridView 可以通過 numOfRow 屬性來指定列數(shù),默認(rèn)值是 3。

這里使用了一些 React 頂層 API,掌握它們,可以做一些有趣的事情。

// GridView.tsx
import { useLayout } from '@react-native-community/hooks'
import { View, StyleSheet, StyleProp, ViewStyle } from 'react-native'
interface GridViewProps {
  style?: StyleProp<ViewStyle>
  numOfRow?: number
  spacing?: number
  verticalSpacing?: number
}
export default function GridView({
  style,
  numOfRow = 3,
  spacing = 16,
  verticalSpacing = 8,
  children,
}: PropsWithChildren<GridViewProps>) {
  const { onLayout, width } = useLayout()
  const itemWidth = (width - (numOfRow - 1) * spacing - 0.5) / numOfRow
  const count = React.Children.count(children)
  return (
    <View style={[styles.container, style]} onLayout={onLayout}>
      {React.Children.map(children, function (child: any, index) {
        const style = child.props.style
        return React.cloneElement(child, {
          style: [
            style,
            {
              width: itemWidth,
              marginLeft: index % numOfRow !== 0 ? spacing : 0,
              marginBottom:
                Math.floor(index / numOfRow) <
                Math.floor((count - 1) / numOfRow)
                  ? verticalSpacing
                  : 0,
            },
          ],
        })
      })}
    </View>
  )
}

現(xiàn)在組合 CheckGroup CheckLabelGridView 三者,看看效果:

嗯,效果很好。

復(fù)用 Context,實(shí)現(xiàn)其它子組件

現(xiàn)在來實(shí)現(xiàn) CheckBox 這個(gè)最為常規(guī)的復(fù)選組件:

// CheckBox.tsx
import { CheckContext, Item } from '../CheckContext'
interface CheckBoxProps<T> {
  item: Item<T>
  style?: StyleProp<ViewStyle>
}
export default function CheckBox({ item, style }: CheckBoxProps<any>) {
  const { checkedItems, setCheckedItems } = useContext(CheckContext)
  const checked = checkedItems?.includes(item)
  return (
    <Pressable
      onPress={() => {
        if (checked) {
          setCheckedItems(checkedItems.filter((i) => i !== item))
        } else {
          setCheckedItems([...checkedItems, item])
        }
      }}
      hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}>
      <View style={[styles.container, style]}>
        <Image
          source={
            checked ? require('./checked.png') : require('./unchecked.png')
          }
        />
        <Text style={[styles.label, checked ? styles.checkedLabel : undefined]}>
          {item.label}
        </Text>
      </View>
    </Pressable>
  )
}

組合 CheckGroupCheckBox,效果如下:

抽取共同狀態(tài)邏輯

CheckLabelCheckBox 有些共同的狀態(tài)邏輯,我們可以把這些共同的狀態(tài)邏輯抽取到一個(gè)自定義 Hook 中。

// CheckContext.ts
export function useCheckContext(item: Item<any>) {
  const { checkedItems, setCheckedItems } = useContext(CheckContext)
  const checked = checkedItems?.includes(item)
  const onPress = () => {
    if (checked) {
      setCheckedItems(checkedItems.filter((i) => i !== item))
    } else {
      setCheckedItems([...checkedItems, item])
    }
  }
  return [checked, onPress] as const
}

于是, CheckLabelCheckBox 的代碼可以簡(jiǎn)化為:

// CheckLabel.tsx
import { Item, useCheckContext } from './CheckContext'
interface CheckLabelProps<T> {
  item: Item<T>
  style?: StyleProp<TextStyle>
  checkedStyle?: StyleProp<TextStyle>
}
export default function CheckLabel({
  item,
  style,
  checkedStyle,
}: CheckLabelProps<any>) {
  const [checked, onPress] = useCheckContext(item)
  return (
    <Pressable onPress={onPress}>
      <Text
        style={[
          styles.label,
          style,
          checked ? [styles.checked, checkedStyle] : undefined,
        ]}>
        {item.label}
      </Text>
    </Pressable>
  )
}
// CheckBox.tsx
import { Item, useCheckContext } from '../CheckContext'
interface CheckBoxProps<T> {
  item: Item<T>
  style?: StyleProp<ViewStyle>
}
export default function CheckBox({ item, style }: CheckBoxProps<any>) {
  const [checked, onPress] = useCheckContext(item)
  return (
    <Pressable
      onPress={onPress}
      hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}>
      <View style={[styles.container, style]}>
        <Image
          source={
            checked ? require('./checked.png') : require('./unchecked.png')
          }
        />
        <Text style={[styles.label, checked ? styles.checkedLabel : undefined]}>
          {item.label}
        </Text>
      </View>
    </Pressable>
  )
}

自由組合父組件與子組件

接下來,我們可以如法炮制 Radio 相關(guān)組件,譬如 RadioGroup RadioLabel RadioButton 等等。

然后可以愉快地把它們組合在一起,本文開始頁面截圖的實(shí)現(xiàn)代碼如下:

// LayoutAndState.tsx
interface Item {
  label: string
  value: string
}
const langs = [
  { label: 'JavaScript', value: 'js' },
  { label: 'Java', value: 'java' },
  { label: 'OBJC', value: 'Objective-C' },
  { label: 'GoLang', value: 'go' },
  { label: 'Python', value: 'python' },
  { label: 'C#', value: 'C#' },
]
const platforms = [
  { label: 'Android', value: 'Android' },
  { label: 'iOS', value: 'iOS' },
  { label: 'React Native', value: 'React Native' },
  { label: 'Spring Boot', value: 'spring' },
]
const companies = [
  { label: '上市', value: '上市' },
  { label: '初創(chuàng)', value: '初創(chuàng)' },
  { label: '國(guó)企', value: '國(guó)企' },
  { label: '外企', value: '外企' },
]
const salaries = [
  { label: '10 - 15k', value: '15' },
  { label: '15 - 20k', value: '20' },
  { label: '20 - 25k', value: '25' },
  { label: '25 - 30k', value: '30' },
]
const edus = [
  { label: '大專', value: '大專' },
  { label: '本科', value: '本科' },
  { label: '研究生', value: '研究生' },
]
function LayoutAndState() {
  const [checkedLangs, setCheckedLangs] = useState<Item[]>([])
  const [checkedPlatforms, setCheckedPlatforms] = useState<Item[]>([])
  const [checkedCompanies, setCheckedCompanies] = useState<Item[]>([])
  const [salary, setSalary] = useState<Item>()
  const [education, setEducation] = useState<Item>()
  return (
    <View style={styles.container}>
      <Text style={styles.header}>你擅長(zhǎng)的語言(多選)</Text>
      <CheckGroup
        checkedItems={checkedLangs}
        onCheckedItemsChanged={setCheckedLangs}>
        <GridView style={styles.grid}>
          {langs.map((item) => (
            <CheckLabel key={item.label} item={item} style={styles.gridItem} />
          ))}
        </GridView>
      </CheckGroup>
      <Text style={styles.header}>你擅長(zhǎng)的平臺(tái)(多選)</Text>
      <CheckGroup
        checkedItems={checkedPlatforms}
        onCheckedItemsChanged={setCheckedPlatforms}>
        <GridView style={styles.grid} numOfRow={2}>
          {platforms.map((item) => (
            <CheckLabel key={item.label} item={item} style={styles.gridItem} />
          ))}
        </GridView>
      </CheckGroup>
      <Text style={styles.header}>你期望的公司(多選)</Text>
      <CheckGroup
        checkedItems={checkedCompanies}
        onCheckedItemsChanged={setCheckedCompanies}>
        <View style={styles.row}>
          {companies.map((item) => (
            <CheckBox key={item.label} item={item} style={styles.rowItem} />
          ))}
        </View>
      </CheckGroup>
      <Text style={styles.header}>你期望的薪資(單選)</Text>
      <RadioGroup checkedItem={salary} onItemChecked={setSalary}>
        <GridView style={styles.grid} numOfRow={4}>
          {salaries.map((item) => (
            <RadioLabel key={item.label} item={item} style={styles.gridItem} />
          ))}
        </GridView>
      </RadioGroup>
      <Text style={styles.header}>你的學(xué)歷(單選)</Text>
      <RadioGroup checkedItem={education} onItemChecked={setEducation}>
        <View style={styles.row}>
          {edus.map((item) => (
            <RadioButton key={item.label} item={item} style={styles.rowItem} />
          ))}
        </View>
      </RadioGroup>
    </View>
  )
}
export default withNavigationItem({
  titleItem: {
    title: 'Layout 和 State 分離',
  },
})(LayoutAndState)
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: 'stretch',
    paddingLeft: 32,
    paddingRight: 32,
  },
  header: {
    color: '#222222',
    fontSize: 17,
    marginTop: 32,
  },
  grid: {
    marginTop: 8,
  },
  gridItem: {
    marginTop: 8,
  },
  row: {
    flexDirection: 'row',
    marginTop: 12,
  },
  rowItem: {
    marginRight: 16,
  },
})

請(qǐng)留意 CheckGroup RadioGroup GridView CheckLabel RadioLabel CheckBox RadioButton 之間的組合方式。

示例

這里有一個(gè)示例,供你參考。

以上就是React Native可復(fù)用 UI分離布局組件和狀態(tài)組件技巧的詳細(xì)內(nèi)容,更多關(guān)于React Native UI分離組件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • React實(shí)現(xiàn)路由返回?cái)r截的三種方式

    React實(shí)現(xiàn)路由返回?cái)r截的三種方式

    最近項(xiàng)目為了避免用戶誤操作導(dǎo)致數(shù)據(jù)丟失,增加返回?cái)r截功能,但是之前由于qiankun的報(bào)錯(cuò)導(dǎo)致這個(gè)功能一直有一些問題,所以專門獨(dú)立搞了一個(gè)專題研究在react中各種方式實(shí)現(xiàn)這個(gè)功能,需要的朋友可以參考下
    2024-05-05
  • React如何利用相對(duì)于根目錄進(jìn)行引用組件詳解

    React如何利用相對(duì)于根目錄進(jìn)行引用組件詳解

    這篇文章主要給大家介紹了關(guān)于React如何使用相對(duì)于根目錄進(jìn)行引用組件的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-10-10
  • react+antd實(shí)現(xiàn)動(dòng)態(tài)編輯表格數(shù)據(jù)

    react+antd實(shí)現(xiàn)動(dòng)態(tài)編輯表格數(shù)據(jù)

    這篇文章主要為大家詳細(xì)介紹了react+antd實(shí)現(xiàn)動(dòng)態(tài)編輯表格數(shù)據(jù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • React自定義hooks同步獲取useState的最新狀態(tài)值方式

    React自定義hooks同步獲取useState的最新狀態(tài)值方式

    這篇文章主要介紹了React自定義hooks同步獲取useState的最新狀態(tài)值方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • Header組件熱門搜索欄的實(shí)現(xiàn)示例

    Header組件熱門搜索欄的實(shí)現(xiàn)示例

    這篇文章主要為大家介紹了Header組件熱門搜索欄的實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-04-04
  • React Native中Navigator的使用方法示例

    React Native中Navigator的使用方法示例

    導(dǎo)航組件Navigator可以讓我們客戶端在不同的頁面見進(jìn)行切換,下面這篇文章主要給大家介紹了關(guān)于React Native中Navigator的使用方法,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-10-10
  • React Native實(shí)現(xiàn)進(jìn)度條彈框的示例代碼

    React Native實(shí)現(xiàn)進(jìn)度條彈框的示例代碼

    本篇文章主要介紹了React Native實(shí)現(xiàn)進(jìn)度條彈框的示例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • React useImperativeHandle處理組件狀態(tài)和生命周期用法詳解

    React useImperativeHandle處理組件狀態(tài)和生命周期用法詳解

    React Hooks 為我們提供了一種全新的方式來處理組件的狀態(tài)和生命周期,useImperativeHandle是一個(gè)相對(duì)較少被提及的Hook,但在某些場(chǎng)景下,它是非常有用的,本文將深討useImperativeHandle的用法,并通過實(shí)例來加深理解
    2023-09-09
  • 淺談react-router HashRouter和BrowserRouter的使用

    淺談react-router HashRouter和BrowserRouter的使用

    本篇文章主要介紹了淺談react-router HashRouter和BrowserRouter的使用,具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-12-12
  • React國(guó)際化react-i18next詳解

    React國(guó)際化react-i18next詳解

    react-i18next 是基于 i18next 的一款強(qiáng)大的國(guó)際化框架,可以用于 react 和 react-native 應(yīng)用,是目前非常主流的國(guó)際化解決方案。這篇文章主要介紹了React國(guó)際化react-i18next的相關(guān)知識(shí),需要的朋友可以參考下
    2021-10-10

最新評(píng)論

青岛市| 灵武市| 宝应县| 靖安县| 喀什市| 曲周县| 霞浦县| 桂林市| 伊金霍洛旗| 长汀县| 吉木乃县| 股票| 龙门县| 河东区| 福清市| 新余市| 金堂县| 南充市| 扶沟县| 灌南县| 天镇县| 新安县| 阜阳市| 微山县| 天长市| 五大连池市| 涟水县| 山阴县| 河南省| 洞头县| 藁城市| 曲松县| 襄汾县| 罗山县| 上犹县| 江西省| 阿克陶县| 长葛市| 福安市| 威远县| 大连市|