哲思简友广场

React-Native(入门)

2019-11-25  本文已影响0人  不思量q
  1. 自定义组件中使用props,在 render函数中引用this.props即可
import React, { Component } from 'react';
import { Text, View } from 'react-native';

class Greeting extends Component {
  render() {
    return (
      <View style={{alignItems: 'center', marginTop: 50}}>
        <Text>Hello {this.props.name}!</Text>
      </View>
    );
  }
}

export default class LotsOfGreetings extends Component {
  render() {
    return (
      <View style={{alignItems: 'center'}}>
        <Greeting name='Rexxar' />
        <Greeting name='Jaina' />
        <Greeting name='Valeera' />
      </View>
    );
  }
}

2.state
工作原理与react一致;
必须使用setState改变状态;
setState是一个merge合并操作,不会影响其他属性;
setState是一个异步操作,也就是说修改不会立即生效。
3.样式
样式名基本遵循了CSS的命名规则,只是要求小驼峰命名;
JS文件中声明一个styles对象即可使用

const styles = StyleSheet.create({
  bigBlue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 30,
  },
  red: {
    color: 'red',
  },
});

4.高度和宽度
指定宽高:无单位,表示逻辑像素点
弹性(Flex)宽高:要求父组件有设置width, height或者flex,容器尺寸不能为0

  1. Flex布局
    flexDirection alignItems justifyContent
    web上的CSS的差异不大,差异在于默认值:flexDirection默认值不再是row而是column,然后flex值只能是数值。
    flex will define how your items are going to **“fill”** over the available space along your main axis. Space will be divided according to each element's flex property.
    详情点击
  2. 文本输入处理
    onChangeText:此属性接受一个函数,而此函数会在文本变化时被调用;
    onSubmitEditing: 在文本被提交后(用户按下软键盘上的提交键)调用;
import React, { Component } from 'react';
import { Text, TextInput, View } from 'react-native';

export default class PizzaTranslator extends Component {
  state = {
    text: ''
  }

  render() {
    return (
      <View style={{padding: 10}}>
        <TextInput
          style={{height: 40}}
          placeholder="Type here to translate!"
          onChangeText={(text) => this.setState({text})}
          value={this.state.text}
        />
        <Text style={{padding: 10, fontSize: 42}}>
          {this.state.text.split(' ').map((word) => word && '').join(',')}
        </Text>
      </View>
    );
  }
}
  1. 触摸事件处理
    RN提供了常见的手势操作,如滑动、点击等,同时也提供了识别更复杂的手势的完整的手势响应系统
<Button onPress={() => { Toast.show('Clicked')}} title='Click Here' />

8.滚动视图
ScrollView适合用来显示数量不多的滚动元素,放在其中的所有元素都会被渲染,所以不是很推荐使用,性能更好的组件可以使用FlatList
9.长列表FlatListSectionList
优势:相比于ScrollView全部元素渲染,FlatList优先渲染当前屏幕的元素。
FlatList组件必须的两个属性是data和renderItem。data是列表的数据源,而renderItem则从数据源中逐个解析数据,然后返回一个设定好格式的组件来渲染。

<FlatList
     keyExtractor={ item => item.name }
     data={ items }
     renderItem={ ({ item }) => this.renderItem(item) }
/>

Section: 渲染分组数据可选择

export default class SectionListBasics extends Component {
  render() {
    return (
      <View style={styles.container}>
        <SectionList
          sections={[
            {title: 'D', data: ['Devin', 'Dan', 'Dominic']},
            {title: 'J', data: ['Jackson', 'James', 'Jillian', 'Jimmy', 'Joel', 'John', 'Julie']},
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
          renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
          keyExtractor={(item, index) => index}
        />
      </View>
    );
  }
}

9.网络请求
fetch

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

处理响应数据

function getMoviesFromApiAsync() {
  return fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies;
    })
    .catch((error) => {
      console.error(error);
    });
}

抑或使用ES7async/await语法

// 注意这个方法前面有async关键字
async function getMoviesFromApi() {
  try {
    // 注意这里的await语句,其所在的函数必须有async关键字声明
    let response = await fetch(
      'https://facebook.github.io/react-native/movies.json',
    );
    let responseJson = await response.json();
    return responseJson.movies;
  } catch (error) {
    console.error(error);
  }
}
上一篇 下一篇

猜你喜欢

热点阅读