image.png

React Native 用于使用 JavaScript和React构建跨平台移动应用程序。自2015年首次发布以来,该库已经发展壮大,并在移动开发者社区中得到了广泛的应用。

实际上,社区对于React Native的成功起到了巨大的作用。似乎每天都有人发布新的库,使得使用React Native构建应用程序变得更加容易。在这个指南中,我们将比较最受欢迎的React Native UI库。

styled-components

styled-components UI库使你能够将CSS编写为React组件,这允许动态样式和自动前缀。该库还支持React Native。在React Native中,你通常会将样式编写为JavaScript对象。然而,将样式编写为组件可以让你编写可读的代码和可复用的组件,并多次使用你的样式,这意味着更少的代码。

例如,你可以使用经典风格的对象,如下所示:

import {StyleSheet, Text, View} from 'react-native'
export default function App() {

return (
  <View
        style={{
          backgroundColor: '#a1cae2',
          borderRadius: 10,
          height: 200,
          width: 150
        }}
      >
        <View
          style={{
            padding: 2
          }}
        >
          <Text
            style={{
              fontSize: 20,
              color: '#000',
              textAlign: 'center'
            }}
          >
            Header
          </Text>
        </View>
        <View
          style={{
            padding: 2,
            display: 'flex',
            alignItems: 'center'
          }}
        >
          <Text
            style={{
              fontSize: 14
            }}
          >
            Lorem ipsum dolor sit amet consectetur adipisicing elit.
          </Text>
        </View>
      </View>

)

}

但是,使用样式化组件,你可以使代码更易读且一致:

import {StatusBar} from 'expo-status-bar'
import React from 'react'
import {StyleSheet, Text, View} from 'react-native'
import styled from 'styled-components/native'

const CardContainer = styled.View`
  background-color: #b34180;
  height: 200px;
  border-radius: 10px;
  width: 150px;
`
const CardHeader = styled.View`
  padding: 2px;
  text-align: center;
`
const CardTitle = styled.Text`
  font-size: 20px;
  text-align: center;
  color: #fff;
`

const CardBody = styled.View`
  padding: 2px;
  align-items: center;
  display: flex;
`
const CardDescription = styled.Text`
  font-size: 14px;
  color: #fff;
  text-align: center;
`

export default function App() {
  return (
    <View style={styles.container}>

      {/* styled component */}
      <CardContainer>
        <CardHeader>
          <CardTitle>Header 2</CardTitle>
        </CardHeader>
        <CardBody>
          <CardDescription>Lorem ipsum dolor sit amet consectetur adipisicing elit.</CardDescription>
        </CardBody>
      </CardContainer>
    </View>
  )
}

在上述代码中,你可以看到两个示例在代码可读性和组件一致性方面的主要区别。在用户界面中,结果仍然会是相同的。

image.png

使用styled-components的另一个原因是,如果你来自CSS世界,它可以让你使用已经熟悉的CSS语法。

React Native 扩展样式表

React Native Extended StyleSheet 是我在 React Native 中进行样式设计的最爱工具之一。尽管它与 React Native 自带的 React Native StyleSheet 抽象类似,但这个库提供了额外的优势,如媒体查询、变量、动态样式和主题。使用 React Native Extended StyleSheet 可以让你的用户界面在多种设备上响应。

总的来说,React Native Extended StyleSheet的使用方式与React Native StyleSheet相同。以下是一个实际示例,展示如何同时使用变量和媒体查询与React Native StyleSheet。

首先,使用 EStyleSheet.build() 方法定义全局变量。通常,你会在主入口文件 App.jsx 中添加这段代码:

EStyleSheet.build({
  /* Smartphones (portrait and landscape) ----------- */
  $primary: '#301551',
  $green:"green",
  $white:'#fff',
  $black:"#000",
  $gray:"#ccc"


});

接下来,使用 EStyleSheet.value('variableName') 获取任何变量的值:

const styles = EStyleSheet.create({
  container: {
    backgroundColor: EStyleSheet.value('$primary'),

  },
});

这是完整的示例:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
} from 'react-native';

import EStyleSheet from 'react-native-extended-stylesheet';
// This file is for a reusable grouping of Theme items.
// Similar to an XML fragment layout in Android

EStyleSheet.build({
  /* Smartphones (portrait and landscape) ----------- */
  $primary: '#301551',
  $green:"green",
  $white:'#fff',
  $black:"#000",
  $gray:"#ccc"



});

const App: () => React$Node = () => {
  return (
    <>
      <View style={styles.container}>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <ScrollView>
            <Text>EStyleSheet </Text>
          </ScrollView>
        </SafeAreaView>
      </View>
    </>
  );
};

const styles = EStyleSheet.create({
  container: {
    width: '100%',
    backgroundColor: EStyleSheet.value('$primary'),
    height: '100%',

    /** IPad */
    '@media (min-width : 768px) and (max-width : 1024px) ': {
      backgroundColor: '#ed8a0a',
    },
  },
});

export default App;

在上文中,我们使得 backgroundColor 在iPad上访问应用时发生改变:

image.png

React Native Elements

React Native Elements 是我最喜欢的React Native UI库,因为它使用简单,有很好的文档,以及在iOS和Android上的优越支持。以下是如何使用这个库的例子:

@copyrights https://reactnativeelements.com/docs/tooltip

import { Tooltip, Text } from 'react-native-elements';

...

<Tooltip popover={<Text>Info here</Text>}>
  <Text>Press me</Text>
</Tooltip>

React Native Paper

React Native Paper 与React Native Elements相当相似。主要的区别在于React Native Paper以Material Design UI作为其UI组件的基础。如果你是Material UI设计系统的粉丝,那么React Native Paper就是你的UI库。

当使用React Native Paper时,你可能会经常使用主题功能。主题功能允许你整合自己的自定义设计系统,可以与库的设计相结合。例如,你可以整合自己的颜色方案,排版等。

在React Native中使用主题功能很简单;只需用 PaperProvider 包裹你的应用,并将你的主题对象传递给它:

import { DefaultTheme, Provider as PaperProvider } from 'react-native-paper';
import Home from '/home'

const theme = {
  colors: {
    primary: '#90eee1',
    accent: '#6356e5',
  },
  fonts:{
    regular:16,
    small:12,
  },
  typography:{
  title:'Roboto',
   paragraph:'Open Sans'  

  }
};

export default function App() {
  return (



  );
}

现在,你可以在应用的任何地方访问主题值,并享受一致的设计系统。要在任何组件中访问主题,你需要使用 withTheme 高阶组件来包装它。

import {View,Text} from 'react-native'
import { withTheme } from 'react-native-paper';


const CardTitle = ({theme})=>{

 return (


     Headline 3



 )
}

export default withTheme(CardTitle)

对移动开发者来说,构建表单可能会很棘手。我们接下来要探讨的UI库可以帮助你节省时间,避免常见的键盘相关问题,比如用户输入时UI视图无响应。

React Native 信用卡输入

React Native Credit Card Input非常易于使用。它拥有漂亮的用户界面和吸引人的动画效果,通过简化信用卡信息的输入,提供了出色的用户体验:

image.png

React Native Credit Card Input 使输入支付信息更加直观。它具有自动完成功能,并处理信用卡号的验证,因此你无需编写任何额外的代码来清理输入。React Native Credit Card Input还提供自定义样式,使你能够集成自己的样式和图标。

以下是如何使用这个UI库的简单示例:

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
} from 'react-native';
import {
  CreditCardInput,

} from 'react-native-credit-card-input';

const App: () => React$Node = () => {
  const _onChange = (e) => {
    /**
     *
     *
     * {"status": {"cvc": "incomplete", "expiry": "incomplete", "number": "invalid"}, "valid": false, "values": {"cvc": "", "expiry": "", "number": "8", "type": undefined}}
     */
    console.log(e.values.number);
    console.log(e.valid);
    console.log(e.values.cvc);
    console.log(e.values.expiry);
  };
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <View>
          <CreditCardInput onChange={_onChange} />
        </View>
      </SafeAreaView>
    </>
  );
};

React Native Credit Card Input最大的优势在于它是一个纯React组件,因此你无需进行任何链接,这与使用类似工具 react-native-awesome-card-io 的情况不同。

Gifted Chat

如果你想在React Native应用中添加聊天功能,Gifted Chat是一个非常棒的库,它能让你通过几个简单的步骤创建一个聊天框的用户界面。该库支持iOS、Android和Web:

image.png

Gifted Chat不需要任何链接,因为它不包含任何原生代码。你可以简单地使用 Yarn 或 npm 安装该包:

yarn add react-native-gifted-chat

这是一个如何开始使用Box UI组件的例子:

# copyright https://github.com/FaridSafi/react-native-gifted-chat
import {GiftedChat} from 'react-native-gifted-chat';
import React, {useCallback,useState} from 'react';

const App: () => React$Node = () => {
  const [messages, setMessages] = React.useState([]);
  React.useEffect(() => {
    setMessages([
      {
        _id: 1,
        text: 'Hello developer',
        createdAt: new Date(),
        user: {
          _id: 2,
          name: 'React Native',
          avatar: 'https://placeimg.com/140/140/any',
        },
      },
    ]);
  }, []);

  const onSend = useCallback((messages = []) => {
    setMessages((previousMessages) =>
      GiftedChat.append(previousMessages, messages),
    );
  }, []);
  return (
    <>
      <View style={styles.container}>
        <StatusBar barStyle="dark-content" />

        <GiftedChat
          messages={messages}
          onSend={(messages) => onSend(messages)}
          user={{
            _id: 1,
          }}
        />
      </View>
    </>
  );
};

react-native-animatable

react-native-animatable 使你能够在React Native中为UI添加过渡和动画。它有一个声明式API组件,你可以将其用作你想要添加动画或过渡的组件的包装器。最好的是,react-native-animatable是可定制的,所以你可以控制过渡的持续时间,延迟和方向。

以下是一个简单过渡的例子:

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  TouchableHighlight,
} from 'react-native';

import * as Animatable from 'react-native-animatable';


const App: () => React$Node = () => {
  const phoneRef = React.useRef(null);
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView>
          <View
            style={{
              borderColor: 'red',
              flex: 1,
              alignItems: 'center',
              justifyContent: 'center',
            }}>
            {/* <LiteCreditCardInput onChange={_onChange} /> */}
            {/* <PhoneInput ref={phoneRef} /> */}
            <Animatable.View animation="slideInDown">
              <TouchableHighlight
                style={{
                  width: 160,
                  height: 160,
                  borderRadius: 8,

                  backgroundColor: '#6155a6',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
                <Text
                  style={{
                    color: '#fff',
                  }}>
                  SlideInDown
                </Text>
              </TouchableHighlight>
            </Animatable.View>
            <Animatable.View animation="slideInLeft">
              <TouchableHighlight
                style={{
                  width: 160,
                  height: 160,
                  borderRadius: 8,

                  backgroundColor: '#fdb827',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
                <Text
                  style={{
                    color: '#fff',
                  }}>
                  SlideInLeft
                </Text>
              </TouchableHighlight>
            </Animatable.View>

            <Animatable.View animation="bounce">
              <TouchableHighlight
                style={{
                  width: 160,
                  height: 160,
                  borderRadius: 8,

                  backgroundColor: '#ff4646',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
                <Text
                  style={{
                    color: '#fff',
                  }}>
                  Bounce
                </Text>
              </TouchableHighlight>
            </Animatable.View>
          </View>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

Lottie

Lottie 是由 Airbnb 开发的一个库,可以转换 Adobe After Effect 动画。它支持iOS、Android和网页。在React Native中, react-native-lottie 命令将允许你通过提供一个组件包装API来使用Lottie动画。它可以像任何React Native库一样安装。

你可以将 LottieView 作为一个组件导入,并传递动画文件的路径。要获取 Lottie 动画,请前往 LottieFiles。以下是在React Native中使用Lottie的示例:

import LottieView from 'lottie-react-native';

<LottieView
  source={require('./images/lottie-af-animation.json')}
  loop
  autoPlay
/>

Vector Icons

Icons in mobile apps 作用类似于道路上的标志:没有它们,你就无法导航。简而言之,图标帮助用户了解如何与你的应用进行交互。

推荐使用矢量图标,因为:

  • 它支持跨平台(iOS,Android,网页,Windows等)。
  • 它配备了流行的图标库,如FontAwesome和MaterialIcons
  • 它易于使用且可定制

这是一个如何使用矢量图标的例子:

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  View,
  Text,
  StatusBar,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
const myIcon = <Icon name="rocket" size={30} color="#900" />;


const App: () => React$Node = () => {
  return (
    <>
      <View style={styles.container}>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <TouchableOpacity>
            <Icon name="chevron-left" color="#000" size={20}/>
            <Text>Click Here</Text>
          </TouchableOpacity>
        </SafeAreaView>
      </View>
    </>
  );
};

React Native SVG

可缩放矢量图形(SVG)是一种基于XML的标记语言,用于描述二维矢量图形。SVG文件旨在以任意尺寸清晰地呈现,并与其他流行的Web标准(如JavaScript、CSS、DOM和SMIL)配合使用。

SVG 在 React Native 中默认不支持,但 React Native SVG 使你能够在iOS和Android上的React Native中渲染SVG。安装非常简单。使用Yarn,只需运行以下命令行:

yarn add react-native-svg 

接下来,使用CocoaPods为iOS安装pods。在终端中,导航到 ios 文件夹:

cd ios 

然后,运行:

pod install

如果你正在使用旧版本的React Native(0.60或更早版本),你需要通过运行以下命令行手动链接包:

react-native link react-native-svg

有两种方式可以使用 React Native SVG。你可以将你的SVG作为一个文件包含进来,如下所示:

import {SvgXml} from 'react-native-svg';
import SVGImage from './images/undraw_happy_2021_h01d.svg';
const App: () => React$Node = () => {
  return (
    <>
      <View style={styles.container}>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <ScrollView>
            <SvgXml width="200" height="200" xml={SVGImage} />  
          </ScrollView>
        </SafeAreaView&gt;
      </View>
    </>
  );
};

image.png

或者,你可以像这样将它作为一个组件来使用:

#@copyrights https://github.com/react-native-svg/react-native-svg
<Svg
  width="130"
  height="130"
  fill="blue"
  stroke="red"
  color="green"
  viewBox="-16 -16 544 544"
>
  <Path
    d="M318.37,85.45L422.53,190.11,158.89,455,54.79,350.38ZM501.56,60.2L455.11,13.53a45.93,45.93,0,0,0-65.11,0L345.51,58.24,449.66,162.9l51.9-52.15A35.8,35.8,0,0,0,501.56,60.2ZM0.29,497.49a11.88,11.88,0,0,0,14.34,14.17l116.06-28.28L26.59,378.72Z"
    strokeWidth="32"
  />
  <Path d="M0,0L512,512" stroke="currentColor" strokeWidth="32" />
</Svg>

React Native Material UI

React Native Material UI是最好和最受欢迎的React Native UI库之一。它在React Native应用程序中实现了Material Design指南。使用React Native Material UI,开发者可以获得预先构建的Material Design组件,包括卡片,对话框,列表项等。

React Native Material UI是基于用户体验和简洁性构建的UI设计模式。它拥有最活跃的社区之一,其文档易于开发人员集成。以下是如何在React Native应用程序中实现React Native Material UI的一个简单示例:

import React from 'react';
import { Card, ListItem, Text } from 'react-native-material-ui';

const App = () => {
  return (
    <Card>
      <ListItem
        centerElement={{
          primaryText: 'React Native Material UI Card',
        }}
      />
      <Text>
        Hello React Native UI
      </Text>
    </Card>
  );
};

export default App;

UI Kitten

UI Kitten是一个流行的UI框架,用于创建可投入生产的React Native应用程序。该库由设计系统驱动,使用Eva设计系统构建。这个框架由多个可自定义的UI组件组成,为开发者提供了创建出色的跨平台移动应用的自由。

与其他React Native UI框架相比,UI Kitten强调通过关注组件性能、内存使用和优化渲染来提供流畅的用户体验。它还提供强大的主题支持,例如允许你在淡色和深色主题之间切换。这提高了产品品牌形象和移动应用的整体设计。

此外,文档易于浏览,社区活跃,为可能在集成UI Kitten时遇到困难的开发者提供了强大的支持。下面是一个在React Native中使用UI Kitten的示例:

import React from 'react';
import { Button } from '@ui-kitten/components';

const App = () => {
  return (
    <Button onPress={() => console.log('Button Pressed')}>
      Press Me!
    </Button>
  );
};

export default App;

总结

现在,你应该已经掌握了为下一个React Native项目选择合适的UI库所需的所有基本信息。然而,值得注意的是,React Native生态系统非常庞大,并且随着社区不断推出新工具以改善开发者体验,其规模还在不断扩大。

要了解React Native生态系统还有什么其他的东西,可以加入Awesome React Native的开源社区。

首发于公众号 大迁世界,欢迎关注。📝 每周一篇实用的前端文章 🛠️ 分享值得关注的开发工具 ❓ 有疑问?我来回答

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及我的系列文章。


王大冶
68.1k 声望105k 粉丝