react native 封装TextInput组件

本文详细介绍了React Native中TextInput组件的封装方法,探讨了其在不同平台上的适配问题,尤其是安卓设备上的键盘输入体验。通过实例展示了如何自定义样式、事件监听及中文输入支持,为开发者提供了一个实用的组件封装方案。

上一篇 react-native文章提到了TextInput组件对安卓的适配问题,因此对该组件进行封装很有必要。

文章地址  react native定报预披项目知识点总结

TextInput介绍

官网地址:

https://facebook.github.io/react-native/docs/textinput

附加中文网地址:https://reactnative.cn/docs/textinput/

TextInput是一个允许用户在应用中通过键盘输入文本的基本组件。本组件的属性提供了多种特性的配置,譬如自动完成、自动大小写、占位文字,以及多种不同的键盘类型(如纯数字键盘)等等。最简单的用法就是丢一个TextInput到应用里,然后订阅它的onChangeText事件来读取用户的输入。

'use strict';
import React, { Component } from 'react'
import PropTypes from 'prop-types'
//import rpx from '../util/unit'

import {
  TextInput,
  StyleSheet,
  Platform,
  Dimensions
} from 'react-native'

const deviceH = Dimensions.get('window').height
const deviceW = Dimensions.get('window').width

const basePx = 750

function rpx(px) {
    return px *  deviceW / basePx
}


export default class Input extends Component{
  constructor(props) {
    super(props)
  }
  static propTypes = {
    value:PropTypes.string
  }
  shouldComponentUpdate(nextProps){
    return Platform.OS !== 'ios' || (this.props.value === nextProps.value &&
           (nextProps.defaultValue == undefined || nextProps.defaultValue == '' )) ||
           (this.props.defaultValue === nextProps.defaultValue &&  (nextProps.value == undefined || nextProps.value == '' ));

  }
  blur() {
    this.refs.textInput.blur()
  }
  render() {
    return (
      <TextInput
        ref="textInput"
        placeholderTextColor='#ccc'
        placeholder={'输入代码、名称或简拼'}
        style={[styles.textInput,this.props.style]}
        underlineColorAndroid="transparent"
        {...this.props}
      />
    )
  }
}
const styles = StyleSheet.create({
  textInput:{
    height:rpx(60),
    fontSize:rpx(30),
    color:'#333',
    backgroundColor:'#fff',
    borderRadius:rpx(4),
    paddingHorizontal:rpx(20),
    paddingVertical: 0
  }
})

 

备注:TextInput组件内容超出加省列号:ellipsizeMode = 'tail' numberOfLines = {1 }

 

注明:IOS下TextInput不能输入中文,需要加上

shouldComponentUpdate(nextProps){
    return Platform.OS !== 'ios' || (this.props.value === nextProps.value &&
           (nextProps.defaultValue == undefined || nextProps.defaultValue == '' )) ||
           (this.props.defaultValue === nextProps.defaultValue &&  (nextProps.value == undefined || nextProps.value == '' ));

  }

关于shouldComponentUpdate 可参考文章:http://www.80iter.com/blog/1512370656110845

 

转载于:https://www.cnblogs.com/zuobaiquan01/p/9776195.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值