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

相關文章
相關標籤/搜索