引言

单选,多选,是很常见的 UI 组件,这里以它们为例,来讲解如何分离布局组件和状态组件,以实现较好的复用性。

假如我们要实现如下需求:

这类 UI 有如下特点:

  • 不管是单选还是多选,都可以有网格布局,我们可以把这个网格布局单独抽离出来,放到一个独立的组件中。
  • 多选有 Label 形式和 CheckBox 形式,表现形式不一样,但是状态逻辑是一样的,我们可以单独封装这个状态逻辑。
  • 单选有 Label 形式和 RadioButton 形式,表现形式不一样,但是状态逻辑是一样的,我们可以单独封装这个状态逻辑。
  • 布局可以很复杂,在某个层级中,才会发生选择行为。

现在让我们一步一步来实现一个设计良好的,可复用的 UI 组件。

包装 Context.Provider 作为父组件

为了实现父子组件的跨层级通讯,我们需要使用 React.Context

首先来实现 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 实际上是个 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 来实现子组件

复选组件有多种表现形式,我们先来实现 CheckLabel。主要是使用 useContext 这个 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>
  )
}

现在组合 CheckGroupCheckLabel,看看效果:

可见,复选功能已经实现,但我们需要的是网格布局哦。好的,现在就去写一个 GridVeiw 来实现网格布局。

使用 React 顶层 API 动态设置样式

我们的 GridView 可以通过 numOfRow 属性来指定列数,默认值是 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>
  )
}

现在组合 CheckGroup CheckLabelGridView 三者,看看效果:

嗯,效果很好。

复用 Context,实现其它子组件

现在来实现 CheckBox 这个最为常规的复选组件:

// 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,效果如下:

抽取共同状态逻辑

CheckLabelCheckBox 有些共同的状态逻辑,我们可以把这些共同的状态逻辑抽取到一个自定义 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 的代码可以简化为:

// 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 相关组件,譬如 RadioGroup RadioLabel RadioButton 等等。

然后可以愉快地把它们组合在一起,本文开始页面截图的实现代码如下:

// 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: '初创', value: '初创' },
  { label: '国企', value: '国企' },
  { 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}>你擅长的语言(多选)</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}>你擅长的平台(多选)</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}>你的学历(单选)</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,
  },
})

请留意 CheckGroup RadioGroup GridView CheckLabel RadioLabel CheckBox RadioButton 之间的组合方式。

示例

这里有一个示例,供你参考。

以上就是React Native可复用 UI分离布局组件和状态组件技巧的详细内容,更多关于React Native UI分离组件的资料请关注Devmax其它相关文章!

React Native可复用 UI分离布局组件和状态组件技巧的更多相关文章

  1. ios – React native链接到另一个应用程序

    如果是错误的,有人知道如何调用正确的吗?

  2. ios – React Native – 在异步操作后导航

    我正在使用ReactNative和Redux开发移动应用程序,我正面临着软件设计问题.我想调用RESTAPI进行登录,如果该操作成功,则导航到主视图.我正在使用redux和thunk所以我已经实现了异步操作,所以我的主要疑问是:我应该把逻辑导航到主视图?我可以直接从动作访问导航器对象并在那里执行导航吗?.我对组件中的逻辑没有信心.似乎不是一个好习惯.有没有其他方法可以做到这一点?

  3. 在ios中使用带有React Native(0.43.4)的cocoapods的正确方法是什么?

    我已经挖掘了很多帖子试图使用cocoapods为本地ios库设置一个反应原生项目,但我不可避免地在#import中找到了丢失文件的错误.我的AppDelegate.m文件中的语句.什么是使用反应原生的可可豆荚的正确方法?在这篇文章发表时,我目前的RN版本是0.43.4,而我正在使用Xcode8.2.1.这是我的过程,好奇我可能会出错:1)

  4. ios – React Native WebView滚动行为无法按预期工作

    如何确保滚动事件的行为与ReactNative应用程序中的浏览器相同?

  5. ios – React Native – BVLinearGradient – 找不到’React/RCTViewManager.h’文件

    谢谢.解决方法几天前我遇到了完全相同的问题.问题是在构建应用程序时React尚未链接.试试这个:转到Product=>Scheme=>管理方案…=>点击你的应用程序Scheme,然后点击Edit=>转到Build选项卡=>取消选中ParallelizeBuild然后点击标志添加目标=>搜索React,选择第一个名为React的目标,然后单击Add然后在目标列表中选择React并将其向上拖动到该列表中的第一个.然后转到Product=>再次清理并构建项目.这应该有所帮助.

  6. ios – React Native – NSNumber无法转换为NSString

    解决方法在你的fontWeight()函数中也许变成:

  7. ios – React native error – react-native-xcode.sh:line 45:react-native:command not found命令/ bin/sh失败,退出代码127

    尝试构建任何(新的或旧的)项目时出现此错误.我的节点是版本4.2.1,react-native是版本0.1.7.我看过其他有相同问题的人,所以我已经更新了本机的最新版本,但是我仍然无法通过xcode构建任何项目.解决方法要解决此问题,请使用以下步骤:>使用节点版本v4.2.1>cd进入[你的应用]/node_modules/react-native/packager>$sh./packager.s

  8. 反应原生 – 如何通过Xcode构建React Native iOS应用程序到设备?

    我试图将AwesomeProject应用程序构建到设备上.构建成功并启动屏幕显示,但后来我看到一个红色的“无法连接到开发服务器”屏幕.它表示“确保节点服务器正在运行–从Reactroot运行”npmstart“.看起来节点服务器已经运行,因为当我做npm启动时,我收到一个EADDRINUSE消息,表示该端口已经在使用.解决方法从设备访问开发服务器您可以使用开发服务器快速迭代设备.要做到这一点,你的

  9. 静音iOS推送通知与React Native应用程序在后台

    我有一个ReactNative应用程序,我试图获得一个发送到JavaScript处理程序的静默iOS推送通知.我看到的行为是AppDelegate中的didReceiveRemoteNotification函数被调用,但是我的JavaScript中的处理程序不会被调用,除非应用程序在前台,或者最近才被关闭.我很困惑的事情显然是应用程序正在被唤醒,并且它的didReceiveRemoteNotifi

  10. 如何为iOS的React Native设置分析

    所以我已经完成了一个针对iOS的ReactNative项目,但是我想在其中分析.我尝试了react-native-google-analytics软件包,但是问题阻止了它的正常工作.此外,react-native-cordova-plugin软件包只适用于Android,因此插入Cordova插件进行分析的能力现在已成为问题.我也没有Swift/ObjectiveC的经验,所以将完全失去GA的插入.有没有人有任何建议如何连接GoogleAnalytics的ReactNativeforiOS?

随机推荐

  1. js中‘!.’是什么意思

  2. Vue如何指定不编译的文件夹和favicon.ico

    这篇文章主要介绍了Vue如何指定不编译的文件夹和favicon.ico,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  3. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  4. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  5. AngularJs上传前预览图片的实例代码

    使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,怎么实现这样的功能呢?今天小编给大家分享AugularJs上传前预览图片的实现代码,需要的朋友参考下吧

  6. JavaScript面向对象编程入门教程

    这篇文章主要介绍了JavaScript面向对象编程的相关概念,例如类、对象、属性、方法等面向对象的术语,并以实例讲解各种术语的使用,非常好的一篇面向对象入门教程,其它语言也可以参考哦

  7. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  8. javascript 动态调整图片尺寸实现代码

    在自己的网站上更新文章时一个比较常见的问题是:文章插图太宽,使整个网页都变形了。如果对每个插图都先进行缩放再插入的话,太麻烦了。

  9. jquery ajaxfileupload异步上传插件

    这篇文章主要为大家详细介绍了jquery ajaxfileupload异步上传插件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. React学习之受控组件与数据共享实例分析

    这篇文章主要介绍了React学习之受控组件与数据共享,结合实例形式分析了React受控组件与组件间数据共享相关原理与使用技巧,需要的朋友可以参考下

返回
顶部