1. 程式人生 > >RN使用筆記二

RN使用筆記二

chang ner 改變 his 刪除 tst png start 所有

---恢復內容開始---

使用命令行打開Android 模擬器

使用android avd

技術分享圖片

使用 emulator -list-avds

可以顯示出所有可用模擬器類型

技術分享圖片

通過 emulator @模擬器名字

如emulator @Nexus_5_API_24 來啟動模擬器

技術分享圖片

在 ios/AppDelegate.m 中聲名根視圖

技術分享圖片

[[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"demo01"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];

getInitialState 可以讓我們創建React組件的初始化狀態(state)

創建render函數前加上

getInitialState: function() {
   return {
         zip: ‘‘   
    };
}

緊接著 在<Text> 組件中的內容為this.state.zip

<Text style={styles.welcome}>

  You input {this.state.zip}

<Text>

同樣 需要一個TextInput 組件 進行輸入

import React , {Component} from ‘react‘;
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    Image,
    TouchableOpacity,
    Alert
} from 
‘react-native‘; class WeatherProject extends Component{ constructor(props) { super(props); this.state = { showValue: ‘‘ } } showData() { alert(this.state.showValue); //展示輸入框的內容 } clickBtn(){ Alert.alert(this.state.showValue); } render(){
return ( <View style={styles.container}> <Text style={styles.welcome}> You input { this.state.showValue } </Text> < TextInput style = { styles.input } onChangeText = {(text) => this.setState({ showValue: text }) } value={this.state.showValue}></TextInput> <TouchableOpacity onPress={() => this.clickBtn()}> <View> <Text>點擊</Text> </View> </TouchableOpacity> </View> ) } } const styles={ container: { flex: 1, justifyContent: ‘center‘, alignItems: ‘center‘, backgroundColor: ‘#f5fcff‘, }, welcome: { fontSize: 20, textAlign: ‘center‘, margin: 10 }, input: { fontSize: 20, borderWidth: 2, height: 40, } } export default WeatherProject;

TextInput 常用方法

class TextInputDemo extends React.Component {
// constructor(props) {
//   super(props);
//   this.state = { text: ‘url Placeholder‘};
// }
    _onChangeText(text) {
        console.log(‘_onChangeText called and text is‘, text);
    }

    _onChange(text) {
        console.log(‘_onChange called and text is‘, text);
    }

    _onEndEditing(text) {
        console.log(‘_onEndEditing called and text is‘, text);
    }

    _onFocus() {
        //點擊某一個item,獲得焦點就會調用這個方法
        console.log(‘_onFocus called‘);
    }

    _onSelectionChange(range) {
        //當在item中選擇的位置發生變化時就會調用這個方法,比如第一次選擇第二個字符的位置,第二次更改為點擊第一個字符位置
        var rangeText = range;
        console.log(‘_onSelectionChange called and range is‘, rangeText);
    }

    _onSubmitEditing(text) {
        console.log(‘_onSubmitEditing called and text is‘, text);
    }

render() {
  return(
      <View>
      <TextInput
      ref = ‘URLTEXTINPUT‘
      style = {{height: 40, borderColor: ‘gray‘, borderWidth: 1}}
      placeholder = ‘URL‘
      onChangeText={(text) => this._onChangeText(text)}
      onChange = {(event)=>this._onChange(‘onChange text: ‘ + event.nativeEvent.text)}
      //onEndEditing 在文本輸入結束後會調用,時機為在某個框體內輸入文字後選擇鍵盤上的完成鍵或者輸入文字後將焦點手動點換到其它item上,或者輸入文字後選擇return按鈕來切換都會調用
      onEndEditing = {(event)=>this._onEndEditing(‘onEndEditing text: ‘ + event.nativeEvent.text)}
      //如果屬性設置了clearTextOnFocus為true,意思是第二次回到同一個itme的時候自動清空裏面的內容,那麽onChangeText就不會被重新調用,那麽保存的還是上一次的值。當判斷值不為空的情況下就會出錯。
      //這種情況下就需要判斷onSelectionChange中的range是否為0來判斷了
      clearTextOnFocus = {true}
      onFocus = {(event) =>this._onFocus}
      returnKeyType = ‘next‘
      onSelectionChange = {(event) =>this._onSelectionChange(event.nativeEvent.selection.start + event.nativeEvent.selection.end)}
      //此回調函數當軟鍵盤的確定/提交按鈕被按下的時候調用此函數。如果multiline={true},此屬性不可用。還有就是輸入文字後選擇enter鍵也會調用此函數,和onEndEditing唯一不同的是,它在輸入框
     // 焦點切換成另外一個輸入框焦點時候不會被調用
     //所以如果想實現類似選擇next按鈕後將焦點自動切換到下一個item項的功能就可以在這個回調函數中實現
      onSubmitEditing = {(event)=>this.refs.USERNAMETEXTINPUT.focus()}
      />

    <TextInput
    ref = ‘USERNAMETEXTINPUT‘
    style = {{height: 40, borderColor: ‘gray‘, borderWidth: 1}}
    placeholder = ‘Username‘
    //當文本框內容變化的時候調用此回調函數,改變後的文字內容會作為參數來傳遞, onChange一樣的情況調用,唯一不同的是參數不支持直接的text字符串來傳遞而已
    onChangeText={(text) => this._onChangeText(text)}
    onChange = {(event)=>this._onChange(‘onChange text: ‘ + event.nativeEvent.text)}
    onEndEditing = {(event)=>this._onEndEditing(‘onEndEditing text: ‘ + event.nativeEvent.text)}
    //如果屬性設置了clearTextOnFocus為true,意思是第二次回到同一個itme的時候自動清空裏面的內容,那麽onChangeText就不會被重新調用,那麽保存的還是上一次的值。當判斷值不為空的情況下就會出錯。
    //這種情況下就需要判斷onSelectionChange中的range是否為0來判斷了
    clearTextOnFocus = {true}
    onFocus = {(event) =>this._onFocus}
    returnKeyType = ‘next‘
    //onSelectionChange 當在文本框中的選擇內容發生變化的時候會調用這個方法, 簡單點兒就是光標位置和上次不同,就會調用。 調用時機包括: 選擇文本, 長點擊重新定位光標位置, 輸入和刪除文字, 光標focus到不同的item時
    //這個特性就可以使用在一種使用場景下,比如 設置了clearTextOnFocus = {true}屬性,清空內容後選擇登錄按鈕,此時需要監測各個輸入框是否已經有內容,那麽用textchange之類的是無法判斷出來的,
    onSelectionChange = {(event) =>this._onSelectionChange(event.nativeEvent.selection.start + event.nativeEvent.selection.end)}
    onSubmitEditing = {(event)=>this.refs.PASSWORDTEXTINPUT.focus()}
/>

    <TextInput
    ref = ‘PASSWORDTEXTINPUT‘
    style = {{height: 40, borderColor: ‘gray‘, borderWidth: 1}}
    placeholder = ‘Password‘
    onChangeText={(text) => this._onChangeText(text)}
    onChange = {(event)=>this._onChange(‘onChange text: ‘ + event.nativeEvent.text)}
    onEndEditing = {(event)=>this._onEndEditing(‘onEndEditing text: ‘ + event.nativeEvent.text)}
    //如果屬性設置了clearTextOnFocus為true,意思是第二次回到同一個itme的時候自動清空裏面的內容,那麽onChangeText就不會被重新調用,那麽保存的還是上一次的值。當判斷值不為空的情況下就會出錯。
    //這種情況下就需要判斷onSelectionChange中的range是否為0來判斷了。如果使用其它的例如changetext方法來判斷結果會得到上次存儲的結果,因為這種情況下是不會調用諸如此類text改變的方法的
    clearTextOnFocus = {true}
    onFocus = {(event) =>this._onFocus}
    enablesReturnKeyAutomatically = {true}
    returnKeyType = ‘go‘
    onSelectionChange = {(event) =>this._onSelectionChange(event.nativeEvent.selection.start + event.nativeEvent.selection.end)}
    onSubmitEditing = {(event)=>this._onSubmitEditing(‘onSubmitEditing text: ‘ + event.nativeEvent.text)}

/>

    </View>
  );
}
}

展現數據

this.state = {
            showValue: ‘‘,
            forecast: {
                main: ‘Clouds‘,
                description: ‘few clouds‘,
                temp: 30
            }
        }
import React , {Component} from ‘react‘;
import {StyleSheet , Text , View } from ‘react-native‘;

class Forecast extends Component{
    render(){
        return(
            <View>
                <Text style={styles.bigText}>
                    {this.props.main}
                </Text>
                <Text style={styles.mainText}>
                    Current conditions: {this.props.description}
                </Text>
                <Text style={styles.bigText}>
                    {this.props.temp} ℃
                </Text>
            </View>
        )
    }
}

var styles = StyleSheet.create({
    bigText: {
        fontSize: 20,
        textAlign: ‘center‘,
        margin: 10,
        color: ‘#FFFFFF‘
    },
    mainText: {
        fontSize: 16,
        textAlign: ‘center‘,
        color: ‘#FFFFFF‘
    }
})

export default Forecast;
<Forecast main={this.state.forecast.main} description={this.state.forecast.description} temp={this.state.forecast.temp}/>
import React , {Component} from ‘react‘;
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    Image,
    TouchableOpacity,
    Alert
} from ‘react-native‘;
import Forecast from ‘./Forecast‘;

class WeatherProject extends Component{
    constructor(props) {
        super(props);
        this.state = {
            showValue: ‘‘,
            forecast: {
                main: ‘Clouds‘,
                description: ‘few clouds‘,
                temp: 30
            }
        }
    }
    showData() {
        alert(this.state.showValue); //展示輸入框的內容
    }
    clickBtn(){
        Alert.alert(this.state.showValue);
    }
    render(){
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>
                    You input {
                        this.state.showValue
                    }
                </Text>
                <Forecast main={this.state.forecast.main} description={this.state.forecast.description} temp={this.state.forecast.temp}/>
                < TextInput style = {
                    styles.input
                }
                onChangeText = {(text) => 
                    this.setState({
                        showValue: text
                    })
                } value={this.state.showValue}></TextInput>
                <TouchableOpacity onPress={() => this.clickBtn()}>
                    <View style={styles.searchBtn}>
                        <Text>點擊</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
}

const styles={
    container: {
        flex: 1,
        justifyContent: ‘center‘,
        alignItems: ‘center‘,
        backgroundColor: ‘#4D4D4D‘,
    },
    welcome: {
        fontSize: 20,
        textAlign: ‘center‘,
        margin: 10
    },
    input: {
        width: 234,
        fontSize: 20,
        borderWidth: 2,
        height: 40,
    },
    searchBtn:{
        padding: 3,
    }
}

export default WeatherProject;

添加背景圖片

使用 ImageBackground組件

ImageBackground
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    Image,
    TouchableOpacity,
    Alert,
    ImageBackground
} from ‘react-native‘;
<ImageBackground source={require(‘./images/bg.png‘)} resizeModel=‘cover‘ style={styles.backdrop}>
.......
</ImageBackground>
import React , {Component} from ‘react‘;
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    Image,
    TouchableOpacity,
    Alert,
    ImageBackground
} from ‘react-native‘;
import Forecast from ‘./Forecast‘;

class WeatherProject extends Component{
    constructor(props) {
        super(props);
        this.state = {
            showValue: ‘‘,
            forecast: {
                main: ‘Clouds‘,
                description: ‘few clouds‘,
                temp: 30
            }
        }
    }
    showData() {
        alert(this.state.showValue); //展示輸入框的內容
    }
    clickBtn(){
        Alert.alert(this.state.showValue);
    }
    render(){
        return (
            <ImageBackground source={require(‘./images/bg.png‘)} resizeModel=‘cover‘ style={styles.backdrop}>
                <View style={styles.container}>
                    <Text style={styles.welcome}>
                        You input {
                            this.state.showValue
                        }
                    </Text>
                    <Forecast main={this.state.forecast.main} description={this.state.forecast.description} temp={this.state.forecast.temp}/>
                    < TextInput style = {
                        styles.input
                    }
                    onChangeText = {(text) => 
                        this.setState({
                            showValue: text
                        })
                    } value={this.state.showValue}></TextInput>
                    <TouchableOpacity onPress={() => this.clickBtn()}>
                        <View style={styles.searchBtn}>
                            <Text>點擊</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            </ImageBackground>
        )
    }
}

const styles={
    container: {
        flex: 1,
        justifyContent: ‘center‘,
        alignItems: ‘center‘,
    },
    backdrop: {
        flex: 1,
        flexDirection: ‘column‘,
    },
    welcome: {
        fontSize: 20,
        textAlign: ‘center‘,
        margin: 10
    },
    input: {
        width: 234,
        fontSize: 20,
        borderWidth: 2,
        height: 40,
    },
    searchBtn:{
        padding: 3,
    }
}

export default WeatherProject;

從web獲取數據

使用fetch接口

fetch(‘http://www.baidu.com‘).then((response) => response.text()).then((responseText) => {console.log(responseText);})

fetch(‘http://tj.nineton.cn/Heart/index/all?city=CHSH000000‘).then((response) => response.json()).then((responseJSON) => {
            console.log(responseJSON.weather[0].now);
            this.setState({
                forecast: {
                    main: responseJSON.weather[0].city_name,
                    description: responseJSON.weather[0].now.text,
                    temp: responseJSON.weather[0].now.temperature
                }
            })
        }).then((error) => {
            console.log(error);
        })
import React , {Component} from ‘react‘;
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    Image,
    TouchableOpacity,
    Alert,
    ImageBackground
} from ‘react-native‘;
import Forecast from ‘./Forecast‘;

class WeatherProject extends Component{
    constructor(props) {
        super(props);
        this.state = {
            showValue: ‘‘,
            forecast: {
                main: ‘-‘,
                description: ‘-‘,
                temp: ‘‘
            }
        }
    }
    clickBtn(){
        // Alert.alert(this.state.showValue);
        var city = this.state.showValue;
        fetch(‘http://tj.nineton.cn/Heart/index/all?city=CH‘ + city).then((response) => response.json()).then((responseJSON) => {
            console.log(responseJSON.weather[0].now);
            this.setState({
                forecast: {
                    main: responseJSON.weather[0].city_name,
                    description: responseJSON.weather[0].now.text,
                    temp: responseJSON.weather[0].now.temperature
                }
            })
        }).then((error) => {
            console.log(error);
        })
    }
    render(){
        return (
            <ImageBackground source={require(‘./images/bg.png‘)} resizeModel=‘cover‘ style={styles.backdrop}>
                <View style={styles.container}>
                    <Text style={styles.welcome}>
                        You input {
                            this.state.showValue
                        }
                    </Text>
                    <Forecast main={this.state.forecast.main} description={this.state.forecast.description} temp={this.state.forecast.temp}/>
                    < TextInput underlineColorAndroid=‘transparent‘ style = {
                        styles.input
                    }
                    onChangeText = {(text) => 
                        this.setState({
                            showValue: text
                        })
                    } value={this.state.showValue}></TextInput>
                    <TouchableOpacity onPress={() => this.clickBtn()}>
                        <View style={styles.searchBtn}>
                            <Text style={styles.searchBtnText}>Search</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            </ImageBackground>
        )
    }
}

const styles={
    container: {
        flex: 1,
        justifyContent: ‘center‘,
        alignItems: ‘center‘,
    },
    backdrop: {
        flex: 1,
        flexDirection: ‘column‘,
    },
    welcome: {
        fontSize: 20,
        textAlign: ‘center‘,
        margin: 10
    },
    input: {
        width: 234,
        fontSize: 20,
        borderBottomWidth: 0.5,
        borderBottomColor: ‘#fff‘,
        height: 40,
    },
    searchBtn:{
        padding: 10,
    },
    searchBtnText:{
        fontSize: 18,
        color: ‘#fff‘,
    }
}

export default WeatherProject;

RN使用筆記二