React Native上手

组件类型

View: 容器组件
Text: 文本组件
TouchableWithoutFeedback: 点击组件,默认不做点击响应,还有其他类型组件,比如TouchableHighlight FlatList: 列表组件
TextInput: 输入框组件,支持多行
ScrollView: 滚动区域组件
常用的大概就这些,对于组件,会有不同的用法,比如文字只能放在Text里使用,数组数据只有传到FlatList里才能正常使用,点击事件只有在Touch开头的容器里才会生效。引入方式,比如:
import { Text, View } from 'react-native'; 具体可以直接上官网:reactnative.cn/

触发事件

也是特定的组件才能触发的,比如onChangeText,规定只有TextInput组件触发
onPress:触摸
onLongPress: 长按
onSubmitEditing: 会在文本被提交后(用户按下软键盘上的提交键)调用

原生外援

如果你需要针对应用的某一部分特别优化,中途换用原生代码编写也很容易。 想要应用的一部分用原生,一部分用React Native也完全没问题 —— Facebook的应用就是这么做的。

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { TheGreatestComponentInTheWorld } from './your-native-code';

class SomethingFast extends Component {
    render() {
        return (
            <View>
                <TheGreatestComponentInTheWorld />
                <Text>上面这个TheGreatestComponentInTheWorld组件完全可以使用原生Objective-C、Java或是Swift来编写 - 开发流程并无二致。
                </Text>
            </View>
        );
    }
}
复制代码

网络请求

Fetch 方法会返回一个Promise,这种模式可以简化异步风格的代码,需要注意的是,安全机制与网页环境有所不同:在应用中你可以访问任何网站,没有跨域的限制。

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
});
复制代码

fetch api

var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
  if (request.readyState !== 4) {
    return;
  }

  if (request.status === 200) {
    console.log('success', request.responseText);
  } else {
    console.warn('error');
  }
};

request.open('GET', 'https://mywebsite.com/endpoint/');
request.send();
复制代码

request send

Props和State

React 把组件看成是一个状态机(State Machines)。通过与用户的交互,实现不同状态,然后渲染 UI,让用户界面和数据保持一致。 React 里,只需更新组件的 state,然后根据新的 state 重新渲染用户界面(不要操作 DOM)。

Fixed 尺寸 & Flex 尺寸

export default class FlexDimensionsBasics extends Component {
  render() {
    return (
      // Try removing the `flex: 1` on the parent View.
      // The parent will not have dimensions, so the children can't expand.
      // What if you add `height: 300` instead of `flex: 1`?
      <View style={{flex: 1}}>
        <View style={{flex: 1, backgroundColor: 'powderblue'}} />
        <View style={{flex: 2, backgroundColor: 'skyblue'}} />
        <View style={{flex: 3, backgroundColor: 'steelblue'}} />
      </View>
    );
  }
}
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值