美文网首页
React Native基础

React Native基础

作者: 南崽 | 来源:发表于2020-04-20 22:41 被阅读0次

点击进入官网

从Hello World开始吧

import React, { Component } from 'react';
import { Text, View } from 'react-native';

export default class HelloWorldApp extends Component {
  render() {
    return (
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
          <Text>Hello, world!</Text>
        </View>
    );
  }
}

组件

  • 上面的代码定义了一个名为HelloWorldApp的新的组件(Component)
  • 组件本身结构可以非常简单——唯一必须的就是在render方法中返回一些用于渲染结构的 JSX语句

props(属性)

import React, { Component } from 'react';
import { Image } from 'react-native';
//插入 Image 组件

export default class Bananas extends Component {
  render() {
    let pic = {
      uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
    };
    return (
      <Image source={pic} style={{width: 193, height: 110}} />
      //插入一个称为source的prop来指定要显示的图片的地址
      //用style的prop来控制其尺寸
    );
  }
}

自定义组件

  • 自定义组件的时候需要在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>
    );
  }
}

State(状态)

  • props是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变
  • 需要改变的数据,我们需要使用state
import React, { Component } from 'react';
import { Text, View } from 'react-native';

class Blink extends Component {
  // 声明state对象
  state = { isShowingText: true };
  
  componentDidMount() {
    // 每1000毫秒对showText状态做一次取反操作
    setInterval(() => {
      this.setState({
        isShowingText: !this.state.isShowingText
      });
    }, 1000);
  }

  render() {
    // 根据当前showText的值决定是否显示text内容
    if (!this.state.isShowingText) {
      return null;
    }

    return (
      <Text>{this.props.text}</Text>
    );
  }
}

export default class BlinkApp extends Component {
  render() {
    return (
      <View>
        <Blink text='有最崎岖的峰峦 成全过你我张狂' />
        <Blink text='江上清辉与圆月 盛进杯光' />
        <Blink text='有最孤傲的雪山 静听过你我诵章' />
        <Blink text='世人惊羡的桥段 不过寻常' />
      </View>
    );
  }
}
  • 每次调用setState时,BlinkApp 都会重新执行 render 方法重新渲染。这里我们使用定时器来不停调用setState,于是组件就会随着时间变化不停地重新渲染

处理文本输入

TextInput是一个允许用户输入文本的基础组件

  • onChangeText的属性,此属性接受一个函数,而此函数会在文本变化时被调用
  • onSubmitEditing的属性,会在文本被提交后(用户按下软键盘上的提交键)调用
import React, { Component, useState } from 'react';
import { Text, TextInput, View } from 'react-native';

export default function PizzaTranslator() {
  const [text, setText] = useState('');
  return (
    <View style={{padding: 10}}>
      <TextInput
        style={{height: 40}}
        placeholder="Type here to translate!"
        onChangeText={text => setText(text)}
        defaultValue={text}
      />
      <Text style={{padding: 10, fontSize: 42}}>
        {text.split(' ').map((word) => word && '🍕').join(' ')}
      </Text>
    </View>
  );

处理触摸事件

  • ReactNative提供了可以处理常见触摸手势(例如点击或滑动)的组件,以及可用于识别更复杂的手势的完整的手势响应系统

显示一个简单按钮

<Button
  onPress={() => {
    Alert.alert("hello!");
  }}
  title="嘿嘿!"
/>

使用滚动视图

  • ScrollView是一个通用的可滚动的容器,您可以在其中加入多个组件和视图,而且这些组件并不需要是同类型的
  • ScrollView可以垂直滚动,也可以水平滚动(通过horizontal属性来设置)
import React, { Component } from 'react';
import { ScrollView, Image, Text } from 'react-native';

export default class IScrolledDownAndWhatHappenedNextShockedMe extends Component {
  render() {
      return (
        <ScrollView>
          <Text style={{fontSize:96}}>Scroll me plz</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>If you like</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>Scrolling down</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>What's the best</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:96}}>Framework around?</Text>
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Image source={{uri: "https://facebook.github.io/react-native/img/favicon.png", width: 64, height: 64}} />
          <Text style={{fontSize:80}}>React Native</Text>
        </ScrollView>
    );
  }
}
  • 可以将ScrollViews配置为允许使用pagingEnabled道具通过滑动手势在视图之间进行分页。在视图之间水平滑动也可以使用ViewPager组件在Android上实现
  • iOS上,带有单个项目的ScrollView可用于允许用户缩放内容。设置maximumZoomScaleminimumZoomScale道具,用户将可以使用捏合展开手势来放大缩小
  • ScrollView适合于显示数量不多的滚动元素

使用长列表

  • FlatList组件用于显示一个垂直滚动列表,其中的元素之间的结构近似而仅数据不同
import React, { Component } from 'react';
import { FlatList, StyleSheet, Text, View } from 'react-native';

export default class FlatListBasics extends Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={[
            {key: 'Devin'},
            {key: 'Dan'},
            {key: 'Dominic'},
            {key: 'Jackson'},
            {key: 'James'},
            {key: 'Joel'},
            {key: 'John'},
            {key: 'Jillian'},
            {key: 'Jimmy'},
            {key: 'Julie'},
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingTop: 22
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
})

详情请点击

网络

使用 Fetch

  • 发起请求
    要从任意地址获取内容的话,只需简单地将网址作为参数传递给 fetch方法即可
fetch('https://mywebsite.com/mydata.json');

Fetch还有可选的第二个参数,可以用来定制HTTP请求一些参数

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

电影列表

import React,{Component} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  Button,
  Alert,
  Image,
  TouchableOpacity,
  TextInput,
  FlatList,
} from 'react-native';

class App extends Component {
  constructor(props){
    super(props);
    this.state={
      msg:"你好,RN",
      movies:[],
    };
  }
  componentDidMount() {
    this.getMovies();
  }
  getMovies=()=>{
    fetch("http://www.endata.com.cn/API/GetData.ashx",{
      method:"post",
      body:'areaId=50&typeId=0&year=0&initial=&pageIndex=1&pageSize=12&MethodName=BoxOffice_GetMovieData_List',
      headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}
    })
    .then(res=>res.json())
    .then(res=>{
      console.log(res);
      this.setState({movies:res.Data.Table})
    })
  }
  render() {
    return (
      <>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <FlatList
          keyExtractor={item=>item.ID}
          data={this.state.movies}
          numColumns={3}
          columnWrapperStyle={styles.row}
          renderItem={({item})=>{
            return(
              <View style={{marginTop:30}}>
                <Image
                style={{width:125,height:160}}
                source={{uri:item.defaultImage}}/>
                <Text style={{marginTop:5,}}>{item.MovieName}</Text>
              </View>
            )
          }}/>
        </SafeAreaView>
      </>
    );
  }
}
const styles = StyleSheet.create({
  center:{justifyContent:"center",alignItems:"center"},
  row:{flexDirection:"row",justifyContent:"space-between",paddingLeft:26,paddingRight:26},
  col:{flex:1,height:180},
  big:{fontSize:48},
  orange:{color:"orange"}
});

export default App;
  • 结果
movie.png

相关文章

网友评论

      本文标题:React Native基础

      本文链接:https://www.haomeiwen.com/subject/ofusihtx.html