ReactNative: 使用輸入框TextInput組件


一、簡介

一個應用程序中,輸入框基本不可或缺,它衍生的搜索功能在很多APP中隨處可見。在iOS開發中,使用的輸入框組件是UITextView和UITextField,在React-Native中使用的則是TextInput組件。TextInput組件可以通過鍵盤將文本輸入到APP的組件,它提供了如自動校驗、占位符、鍵盤樣式、焦點函數等很多豐富的功能。

 

二、API

TextInput組件提供的屬性和事件基本能夠滿足開發需求,既可以使用它做基本的輸入功能,也能做列表補全的搜索功能。TextInput組件主要屬性和事件如下:

屬性或者函數 作用
autoCapitalize
枚舉類型,用於信息提示,可選值包括none、sentences、words、characters
placeholder
占位符,在輸入前顯示文本內容
value
文本框輸入的內容
placeholderTextColor
占位符文本的顏色
password
如果為true,顯示為密碼輸入框,文本顯示為"*"號
multiline
如果為true,則是多行輸入
editable
如果為false,文本框不可以輸入,默認為true
 
keyboardType
 
   枚舉類型,表示鍵盤類型,可選值包括'default','email-address','numeric','phone-pad','ascii-capable','numbers-and-punctuation','url','number-pad','name-phone-pad','decimal-pad','twitter','web-search',
autoFocus
如果為true,將自動聚焦
clearButtonMode
枚舉類型,用於顯示清除按鈕,可選值包括never、while-editing、unless-editing、always
maxLength
能夠輸入的最長字符數
enablesReturnKeyAutomatically
如果為true,表示無文本時鍵盤不顯示返回鍵,默認為false
returnKeyType
枚舉類型,表示鍵盤返回鍵顯示的字符串,可選值包括default、go、google、join、next、route、search、send、yahoo、done、emergency-call
securityEntry
如果為true,則像密碼框一樣隱藏輸入內容,默認為false
onchangeText
當文本的輸入框內容發生改變時調用。它會接收一個文本的參數對象
onChange
當文本發生改變時,調用該函數
onEndEditing
當結束編輯時,調用該函數
onBlur
失去焦點觸發事件
onFocus
獲取焦點觸發事件
onsubmitEditing
當結束編輯后,點擊鍵盤的提交按鈕時觸發事件
 
        

 

三、使用

1、作為輸入框 

InputView.js

import React, { Component } from 'react';

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

export default class InputView extends Component{

    constructor(props){
        super(props);
        this.state = {content:"當前無內容"}
    }

    render(){
        return (
            <View style={styles.flex}>
                <View style={styles.content}>
                    <Text style={styles.text}>{this.state.content}</Text>
                </View>
                <View style={styles.flex}>
                    <TextInput
                        style={styles.input}
                        placeholder='請輸入您想要的東西'
                        placeholderTextColor={"#CCC"}
                        returnKeyType='done'
                        clearButtonMode='while-editing'
                        enablesReturnKeyAutomatically={true}
                        editable={true}
                        maxLength={100}
                        keyboardType='default'
                        onFocus={()=> console.log("--獲取焦點觸發事件--")}
                        onBlur={()=> console.log("--失去焦點觸發事件--")}
                        onChange={() => console.log("---當文本發生改變時,調用該函數--")}
                        onEndEditing={() => console.log("--當結束編輯時,調用該函數--")}
                        onSubmitEditing={ () => console.log("--當結束編輯后,點擊鍵盤的提交按鈕時觸發事件--")}
                        onChangeText={(text) => this.setState({content:text})}
                    />
                </View>
            </View>
        )
    }

}

const styles = StyleSheet.create({
    flex:{
        flex: 1
    },
    content:{
        height: 200,
        backgroundColor:"red",
        justifyContent: 'center',
        alignItems:'center'
    },
    input:{
        height:45,
        borderWidth: 1,
        marginTop: 20,
        marginRight:5,
        marginLeft: 5,
        paddingLeft: 5,
        borderColor:'#CCC',
        borderRadius: 4
    },
    text:{
        fontSize:20,
        color:'white',
        textAlign:'center'
    }
})

index.ios.js

/** * Sample React Native App * https://github.com/facebook/react-native * @flow */

import React, { Component } from 'react';
import InputView from './src/InputView'

import {
  AppRegistry,
  View
} from 'react-native';

export default class ReactNativeDemo extends Component {

  render() {
    return (
        <View style={{flex: 1}}>
          <InputView/>
        </View>
    );
  }
}

AppRegistry.registerComponent('ReactNativeDemo', () => ReactNativeDemo);

日志和gif如下:

2019-12-12 18:28:43.022 [info][tid:com.facebook.react.JavaScript] --獲取焦點觸發事件--
2019-12-12 18:28:48.992 [info][tid:com.facebook.react.JavaScript] ---當文本發生改變時,調用該函數--
2019-12-12 18:28:49.951 [info][tid:com.facebook.react.JavaScript] ---當文本發生改變時,調用該函數--
2019-12-12 18:28:51.016 [info][tid:com.facebook.react.JavaScript] ---當文本發生改變時,調用該函數--
2019-12-12 18:28:52.893 [info][tid:com.facebook.react.JavaScript] ---當文本發生改變時,調用該函數--
2019-12-12 18:28:55.243 [info][tid:com.facebook.react.JavaScript] --當結束編輯后,點擊鍵盤的提交按鈕時觸發事件--
2019-12-12 18:28:55.248 [info][tid:com.facebook.react.JavaScript] --當結束編輯時,調用該函數--
2019-12-12 18:28:55.256 [info][tid:com.facebook.react.JavaScript] --失去焦點觸發事件--

 

2、制作搜索框

InputSearchView.js

import React, { Component } from 'react';

import {
    StyleSheet,
    View,
    Text,
    TextInput,
    PixelRatio
} from 'react-native'

export default class InputSearchView extends Component{

    constructor(){
        super();
        this.state = {show:false, keywords:""}
    }

    show = () => {
        this.setState({show:this.state.keywords.length>0})
    };

    render(){
        return (
            <View style={styles.flex}>
                <View style={[styles.flexDirection,styles.height]}>
                    <View style={styles.flex}>
                        <TextInput
                            value={this.state.keywords}
                            style={styles.input}
                            placeholder='請輸入關鍵字'
                            placeholderTextColor={"#CCC"}
                            returnKeyType='search'
                            clearButtonMode='while-editing'
                            enablesReturnKeyAutomatically={true}
                            onChangeText={ (text) => this.setState({keywords:text})}
                            onEndEditing={this.show.bind(this)}
                        />
                    </View>
                    <View style={styles.btn}>
                        <Text style={styles.text} onPress={this.show.bind(this)}>
                            搜索
                        </Text>
                    </View>
                </View>
                {
                    this.state.show?
                    <View style={styles.list}>
                        <Text style={styles.list_item}>I AM XYQ</Text>
                        <Text style={styles.list_item}>T FROM CHINA</Text>
                        <Text style={styles.list_item}>I AM 28 YEARS OLD</Text>
                        <Text style={styles.list_item}>WELCOME TO ME</Text>
                    </View> : null
                }

            </View>
        )
    }
}

const styles = StyleSheet.create({
    flex:{
        flex: 1
    },
    flexDirection:{
        flexDirection: 'row'
    },
    list:{
        marginTop: 28,
        height: 200,
        marginLeft: 5,
        marginRight: 5,
        borderColor:"red",
        borderTopWidth: 1/PixelRatio.get(),
    },
    list_item:{
        fontSize:20,
        fontWeight:'bold',
        padding: 5,
        paddingTop: 10,
        paddingBottom: 10,
        borderWidth: 1/PixelRatio.get(),
        borderColor: 'red',
        borderTopWidth: 0
    },
    height:{
        height: 45
    },
    input:{
        height:45,
        borderWidth: 1,
        fontSize:20,
        marginTop: 25,
        marginLeft: 5,
        paddingLeft: 5,
        borderColor:'#CCC',
        borderRadius: 4
    },
    btn:{
        width:60,
        height:45,
        borderWidth: 1,
        marginTop: 25,
        marginRight: 5,
        paddingLeft: 5,
        backgroundColor:'#23BEFF',
        borderColor:'#CCC',
        borderTopRightRadius:4,
        borderBottomRightRadius:4,
        justifyContent: 'center',
        alignItems:'center'
    },
    text:{
        fontSize:20,
        color:'white',
        fontWeight:'bold',
        textAlign:'center'
    }
})

index.ios.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import InputSearchView from './src/InputSearchView'

import {
  AppRegistry,
  View
} from 'react-native';

export default class ReactNativeDemo extends Component {

  render() {
    return (
        <View style={{flex: 1}}>
          <InputSearchView/>
        </View>
    );
  }
}

AppRegistry.registerComponent('ReactNativeDemo', () => ReactNativeDemo);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM