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);

posted @ 2019-12-13 13:24  XYQ全哥  阅读(2128)  评论(0编辑  收藏  举报