上一篇 react-native文章提到了TextInput組件對安卓的適配問題,所以對該組件進行封裝頗有必要。javascript
文章地址 react native定報預披項目知識點總結html
官網地址:java
https://facebook.github.io/react-native/docs/textinputreact
附加中文網地址:https://reactnative.cn/docs/textinput/ios
TextInput是一個容許用戶在應用中經過鍵盤輸入文本的基本組件。本組件的屬性提供了多種特性的配置,譬如自動完成、自動大小寫、佔位文字,以及多種不一樣的鍵盤類型(如純數字鍵盤)等等。最簡單的用法就是丟一個TextInput
到應用裏,而後訂閱它的onChangeText
事件來讀取用戶的輸入。git
'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 }github
註明:IOS下TextInput不能輸入中文,須要加上react-native
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/1512370656110845post