react native入门及学习总结

环境搭建参考官网javascript

hello worldjava

import React from 'react';
import {
  //样式对象
  StyleSheet,
  //视图组件
  View,
  //文本组件
  Text,
} from 'react-native'

const App= () => {
  //定义视图的JSX对象
  //JSX对象只能有1个根对象
  //建立 UI 时最基础的组件view。相似于网页中的div
  //文本的内容须要放置到Text组件中
  return (
    <>
      <View style={styles.view}>
        <Text>helloworld</Text>
      </View>
    </>
  );
};

//定义样式对象
const styles = StyleSheet.create({
  view: {
    height:200,
    width:200,
    //驼峰命名法,第二个单词首字母大写
    backgroundColor: "rgba(200,255,0,0.5)",
  },
});

//导出组件
export default App;

样式react

{/* 没有样式继承的,每个组件都要单独设置样式 */}
<View style ={[styles.txt,{color:'#333300'}]}>
<Text>88888</Text>
</View>
{/* 直接设置样式对象 */}
<View style={styles.card}></View>
{/* 建立样式对象 */}
<View style={{marginTop:8,marginBottom:8,height:100,backgroundColor:'blue'}}></View>
{/* 合并多个样式对象,一样的设置,右边的优先级越高 */}
<View style={[styles.card, {backgroundColor:'yellow'}]}></View>

登陆页面小案例git

import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native'

class Inputs extends Component {
   state = {
      email: '',
      password: '',
      intro:'',
   }
   handleEmail = (text) => {
      this.setState({ email: text })
   }
   handlePassword = (text) => {
      this.setState({ password: text })
   }

   handleIntro = (text) => {
      this.setState({ intro: text })
   }

   register = (email, pass,intro) => {
      alert('email: ' + email + '\npassword: ' + pass + "\nintro:" + intro)
   }
   render() {
      return (
         <View style = {styles.container}>
            <TextInput 
               style = {styles.input}
              // 下划线的颜色,透明则为 transparent
               underlineColorAndroid = "transparent"
               //占位符
               placeholder = "请输入邮箱"
              //  占位符的字体颜色
               placeholderTextColor = "#ccc"
              //  字母大写模式:'none', 'sentences', 'words', 'characters'
               autoCapitalize = "none"
              //  键盘类型,可选的值有 "default","number-pad","decimal-pad", "numeric","email-address","phone-pad"
               keyboardType = "email-address"
              //  键盘上的返回键类型,可选的值有 "done","go","next","search","send"
               returnKeyType = "next"
              //  文本变动后的回调函数,参数为输入框里的文本
               onChangeText = {this.handleEmail}/>

            <TextInput 
               style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "请输入密码"
               placeholderTextColor = "#ccc"
               autoCapitalize = "none"
               returnKeyType = "next"
              //  是否属于密码框类型
               secureTextEntry = {true}
               onChangeText = {this.handlePassword}/>

            <TextInput 
               style = {[styles.input,{height:100}]}
               underlineColorAndroid = "transparent"
               placeholder = "请输入描述"
               placeholderTextColor = "#ccc"
               autoCapitalize = "none"
              //  多行设置
               multiline = {true}
              //  行数
               numberOfLines = {4}
               //文字的位置靠上
               textAlignVertical="top"
               returnKeyType="done"
               onChangeText = {this.handleIntro}/>
            {/* 封装视图,使其能够正确响应触摸操做 */}
            <TouchableOpacity
               style = {styles.submitButton}
               onPress = {
                  () => this.register(this.state.email, this.state.password,this.state.intro)
               }>
               <Text style = {styles.submitButtonText}>注册</Text>
            </TouchableOpacity>
         </View>
      )
   }
}
export default Inputs

const styles = StyleSheet.create({
   container: {
      paddingTop: 23
   },
   input: {
      margin: 15,
      paddingLeft:8,
      height: 40,
      borderColor: '#eeeeee',
      borderWidth: 1
   },
   submitButton: {
      backgroundColor: '#7a42f4',
      padding: 10,
      alignItems:'center',
      margin: 15,
      height: 40,
   },
   submitButtonText:{
      color: 'white'
   }
})

图片组件github

import React, { Component } from 'react';
import { AppRegistry, View, Image,ScrollView } from 'react-native';

export default class App extends Component {
  render() {
    return (
      <ScrollView>
         {/* 普通图片设置 */}
        <Image
          source={require('./assets/1.png')}
        />
        {/* 网络图片设置 */}
        <Image
          style={{margin:10,width: 177, height: 100}}
          source={{uri: 'https://www.twle.cn/static/i/img1.jpg'}}
        />
        {/* 图片显示模式,contain,安装正常的比例缩放到整个能够恰好放进来 */}
        <Image
          style={{margin:10,width: 200, height: 200,resizeMode:'contain',borderWidth:1,borderColor:'#000'}}
          source={require('./assets/img1.jpg')}
        />
        {/* 不会变形,放大图片至恰好覆盖住整个内容 */}
        <Image
          style={{margin:10,width: 200, height: 200,resizeMode:'cover',borderWidth:1,borderColor:'#000'}}
          source={require('./assets/img1.jpg')}
        />
        {/* 直接将图片拉升成设置的大小,会变形 */}
        <Image
          style={{margin:10,width: 200, height: 200,resizeMode:'stretch',borderWidth:1,borderColor:'#000'}}
          source={require('./assets/img1.jpg')}
        />
      </ScrollView>
    );
  }
}

动画组件json

import React, { Component } from 'react';
import { ActivityIndicator, View, Text, TouchableOpacity, StyleSheet,Button } from 'react-native';

class App extends Component {
   state = { animating: true }

   closeActivityIndicator = () => {
      this.setState({animating:!this.state.animating })
      
   }

   //生命周期函数
   componentDidMount = () => this.closeActivityIndicator()
   render() {
      const animating = this.state.animating
      return (
         <View style = {styles.container}>
            {/* 活动指示器,切换animating属性进行显示隐藏切换 */}
            <ActivityIndicator
               animating = {animating}
               color = '#bc2b78'
               size = "large"
               style = {styles.activityIndicator}/>
            <Button onPress={this.closeActivityIndicator} title="切换显示loading"></Button>
         </View>
      )
   }
}
export default App

const styles = StyleSheet.create ({
   container: {
      flex: 1,
      marginTop: 70
   },
   activityIndicator: {
      height: 80
   }
})

弹框react-native

import React from 'react'
import { Alert, Text, TouchableOpacity, StyleSheet, View } from 'react-native'

const App = () => {

    const showAlert1 = () =>{
        Alert.alert('发送数据成功')
    }
    const showTip = () => {
      Alert.alert('删除数据成功')
    }
    const showAlert2 = () =>{
      Alert.alert(
          '警告',
          '确认删除?',
          [
              {text: '确认', onPress: () => showTip()},
              {text: '取消', style: 'cancel'}, 
          ],
          {cancelable: false}
      )
   }

    return (
       <View style={{alignItems:"center"}}>
         <TouchableOpacity onPress = {showAlert1} style = {styles.button}>
            <Text>发送</Text>
         </TouchableOpacity>
         <TouchableOpacity onPress = {showAlert2} style = {styles.button}>
            <Text>删除</Text>
        </TouchableOpacity>
        
        </View>
    )
}
export default App

const styles = StyleSheet.create ({
    button: {
        backgroundColor: '#4ba37b',
        width: 100,
        height:50,
        borderRadius: 50,
        justifyContent:'center',
        alignItems: 'center',
        marginTop: 100,
    }
})

数据存储组件api

import React, { Component } from 'react'
import { Text, View, Alert,TextInput, StyleSheet,TouchableHighlight } from 'react-native'
import { AsyncStorage } from "react-native"

export default class App extends Component {
   state = {
      'name': '老陈,你胖吗?',
      'inputText':'不是清楚,最近体重称坏了,会多转1圈,才显示十几斤',
   }

   async readName() {
        try {
         //   读取数据
          const value = await AsyncStorage.getItem('name')
          if(value !== null) {
              this.setState({ 'name': value })
          }
          Alert.alert("读取数据成功")
        } catch(e) {
          console.log(e);
          Alert.alert("读取数据失败!")
        }
   }

   setName = () => {
      // 保存数据
      AsyncStorage.setItem('name', this.state.inputText);
      Alert.alert("保存成功!")
   }
   render() {
      return (
         <View style = {styles.container}>
            <TextInput 
              style = {styles.textInput} 
              autoCapitalize = 'none' 
              value={this.state.inputText} />
            <View style={{flexDirection:'row'}}>
                <TouchableHighlight style={[styles.button,{marginRight:8}]} onPress={this.setName}>
                    <Text style={styles.buttonTxt}>保存</Text>
                </TouchableHighlight>
                <TouchableHighlight style={[styles.button,{backgroundColor:'blue'}]} onPress={this.readName.bind(this)}>
                    <Text style={styles.buttonTxt}>读取</Text>
                </TouchableHighlight>
            </View>
            <View style={{marginTop:8}}>
                <Text>当前的值:{this.state.name}</Text>
            </View>
         </View>
      )
   }
}

const styles = StyleSheet.create ({
   container: {
      margin:10
   },
   textInput: {
      margin: 5,
      height: 44,
      width:'100%',
      borderWidth: 1,
      borderColor: '#dddddd'
   },
   button: {
      flex:1,
      height:44,
      justifyContent:'center',
      alignItems:'center',
      width:100,
      backgroundColor: 'red'
   },
   buttonTxt:{
      justifyContent:'center',
      color:'#ffffff'
   }
})

动画组件xcode

import React, { Component } from 'react'
import { View, StyleSheet, Animated, TouchableOpacity } from 'react-native'

class App extends Component {
   UNSAFE_componentWillMount = () => {
      //建立动画属性对象
      this.animatedWidth = new Animated.Value(50)
      this.animatedHeight = new Animated.Value(100)
   }
   animatedBox = () => {
      //点击后,设置动画变化
      Animated.timing(this.animatedWidth, {
         toValue: 200,
         duration: 1000
      }).start()
      Animated.timing(this.animatedHeight, {
         toValue: 500,
         duration: 500
      }).start()
   }
   render() {
      const animatedStyle = {
            width: this.animatedWidth, 
            height: this.animatedHeight }
      return (
         <TouchableOpacity 
            style = {styles.container} 
            onPress = {this.animatedBox}>
            <Animated.View style = {[styles.box, animatedStyle]}/>
         </TouchableOpacity>
      )
   }
}
export default App

const styles = StyleSheet.create({
   container: {
      justifyContent: 'center',
      alignItems: 'center'
   },
   box: {
      backgroundColor: 'blue',
      width: 50,
      height: 100
   }
})

开关switch组件网络

import React, { Component } from 'react'
import { View, Text, Switch, StyleSheet, Alert } from 'react-native'

export default class App extends Component {
   constructor() {
      super();
      this.label = { false: '关', true: '开' }
      this.state = {
         switch1Value: true,
      }
   }

   toggleSwitch = (value) => {
      this.setState({ switch1Value: value })
   }

   render() {
      return (
         <View style={styles.container}>
            <Switch
               //某一项被选中时执行此回调。
               onValueChange={this.toggleSwitch}
               value={this.state.switch1Value}
            />
            <View><Text>Switch 当前的状态是:{this.label[this.state.switch1Value]}</Text></View>
         </View>
      )
   }
}

const styles = StyleSheet.create({
   container: {
      flex: 1,
      alignItems: 'center',
      marginTop: 100
   }
})

选项框组件

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

class App extends Component {

   users = [
      {label: '请选择性别',value:''},
      {label: '男',value:'male'},
      {label: '女',value:'female'},
      {label: '其它',value:'other'}
   ]
   state = {user: ''}
   updateUser = (user) => {
      this.setState({ user: user })
   }
   render() {
      return (
         <View style={styles.container}>
            <Text style = {styles.label}>请选择性别</Text>
            {/* 设置选择器 */}
            <Picker 
               selectedValue = {this.state.user} 
               onValueChange = {this.updateUser}>
            {  
               // 设置选项
               this.users.map((o,index) =>
                  <Picker.Item label={o.label} value = {o.value}/>
               )
            }
            </Picker>
            <Text style = {styles.label}>你的选择是</Text>
            <Text style = {styles.text}>{this.state.user}</Text>
         </View>
      )
   }
}
export default App

const styles = StyleSheet.create({

   container: {
      margin:50,
   },
   label: {
      fontSize: 14,
      color:'#333333'
   },
   text: {
      fontSize: 30,
      alignSelf: 'center',
      color: 'red'
   }
})

网络请求

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

var REQUEST_URL = "https://raw.githubusercontent.com/facebook/react-native/0.51-stable/docs/MoviesExample.json";

export default class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         movies: null,
      };
      //绑定事件,用箭头函数能够省略
      this.fetchData = this.fetchData.bind(this);
   }

   //componentDidMount() 会在组件挂载后(插入 DOM 树中)当即调用
   componentDidMount() {
      this.fetchData();
   }

   //发起请求
   fetchData() {
      fetch(REQUEST_URL)
         .then((response) => response.json())
         .then((responseData) => {
            this.setState({
               movies: responseData.movies,
            });
         });
   }

   render() {
      if (!this.state.movies) {
         return this.renderLoadingView();
      }
      var movie = this.state.movies[0];
      return this.renderMovie(movie);
   }

   //loding页面
   renderLoadingView() {
      return (
         <View style={styles.container}>
            <Text>loading...</Text>
         </View>
      );
   }

   //获取数据渲染页面
   renderMovie(movie) {
      return (
         <View style={styles.container}>
            <Image
               style={styles.thumbnail}
               source={{ uri: movie.posters.thumbnail }}
            />
            <View style={styles.rightContainer}>
               <Text style={styles.title}>{movie.title}</Text>
               <Text style={styles.year}>{movie.year}</Text>
            </View>
         </View>
      );
   }

}

const styles = StyleSheet.create({
   container: {
      flex: 1,
      flexDirection: 'row',
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: '#F5FCFF',
   },
   thumbnail: {
      width: 100,
      height: 80
   },
   rightContainer: {
      flex: 1
   },
   title: {
      fontSize: 20,
      marginBottom: 8,
      textAlign: 'center'
   },
   year: {
      textAlign: 'center'
   }
});

其余、安卓APP打包方式参考官网

苹果APP打包须要使用mac端xcode

相关文章
相关标签/搜索