React Native 入门基础

    科技2022-09-04  165

    一、前言 React Native是Facebook推出的使用React和平台原生功能来构建Android和iOS应用的开源移动跨平台框架;

    -视图(Views)和移动开发 在Android和iOS移动应用中,一个视图是UI的基本组成部分:屏幕上的一个小矩形元素、可用于显示文本、图像、和响应用户输入。某些视图也可以包含其他视图,全部都是视图;

    -原生组件 在Android开发中是使用Java或者Kotlin来编写视图,在iOS开发中是使用Object-C和Swift来编写视图,在React Native中则是使用React组件通过JavaScript来调用这些视图;在运行时,React Native为这些组件创建相应的Android和iOS视图;由于React Native组件就是对Android和iOS原生视图的封装,因此使用React Native编写的应用外观、感觉和性能和其他任何原生应用一样;我们将这些平台支持的组件称之为原生组件;

    -核心组件 React Native中有一些基本的,随时可用的原生组件,这些组件就是React Native中的核心组件; 我们常用的核心组件主要有以下:

    ReactNative UI ComponentAndroid ViewiOS View<View>ViewGroupUIView<Text>TextViewUITextView<Image>ImageViewUIImageView<TextInput>EditTextUITextField<ScrollView>ScrollViewUIScrollView

    -React 基础 React Native是通过使用React 组件和JavaScript来编写的,所以我们肯定是要学习 React的,最起码是基本的React 基础; React中的核心概念 JSX、Component、props、state (1)JSX JSX即JavaScript XML,是一种语法糖,可以在JavaScript中写HTML的一种语法;

    import React from 'react' import { View, Text, } from 'react-native'; export default function CustomComponent(){ return ( <View> <Text>自定义组件</Text> </View> ) }

    上面就是在JavaScript 函数CustomComponent中编写了HTML代码即 返回的< View >…这一块代码;,这就是JSX

    (2)Component React是组件化的,即通过使用React 提供的一些组件组成复杂的UI; 上面我们也学习了一些核心组件; 除了React Native提供的一些核心组件,我们也可以自定义组件,自定义组件我们可以定义函数式组件,也可以定义class组件 ;

    -函数式组件

    import React from 'react' import { View, Text, } from 'react-native'; export default function CustomComponent(){ return ( <View> <Text>自定义组件</Text> </View> ) }

    -class组件

    import React ,{Component} from 'react' import { View, Text, } from 'react-native'; export default class CustomComponent extends Component{ render(){ return ( <View> <Text>自定义组件</Text> </View> ) } }

    使用组件: < CustomComponent />

    (3)props props即propertites的简写,属性的意思,因为React是组件化的,我们定义一个 组件时,可以给组件定义一些属性来描述组件的特性;

    import React from 'react' import { View, Text, } from 'react-native'; export default function CustomComponent(props){ return ( <View> <Text>自定义组件{props.name}</Text> </View> ) } import React ,{Component} from 'react' import { View, Text, } from 'react-native'; export default class CustomComponent extends Component{ constructor(props){ super(props) } render(){ return ( <View> <Text>自定义组件{this.props.name}</Text> </View> ) } }

    使用组件 < CustomComponent name=‘组件’> (4)state 上面我们学习了组件的props,而state是组件中的另外一个重要的概念,state即 状态;比如用户操作页面之后,希望页面显示的数据发生相应变化,这个时候就 需要重新渲染页面;对于这种需求,我们就可以把数据放在state中,操作页面之 后,我们只需要修改state,页面就会重新渲染;

    import React, {Component} from 'react'; import {View, Text,TouchableHighlight} from 'react-native'; export default class CustomComponent extends Component { constructor(props) { super(props); this.state={ num:0 } } render() { return ( <View> <TouchableHighlight onPress={()=>{ this.setState({ num:++this.state.num }) }}> <Text>{this.state.num}</Text> </TouchableHighlight> </View> ); } }
    Processed: 0.008, SQL: 9