React Native 小記 - LessBorderTextInput 無邊框的 TextInput
由於 TextInput 在 Android 和 iOS 平臺預設表現不一致,為了統一樣式,這裡參照官方文件(ofollow,noindex">英文文件
|中文文件
)進行了封裝,並添加了對ref
的支援。ref
用於獲取元件,實現自動切換輸入框的焦點等場景。
程式碼展示
import React from 'react'; import {Platform, TextInput,} from 'react-native'; //沒有底部下劃線的輸入框 export default class LessBorderTextInput extends React.Component { componentDidMount() { if (this.props.onRef != null) { this.props.onRef(this) } } focus() { this.textInput.focus() } render() { let mView; if (Platform.OS === 'android') { mView = <TextInput {...this.props} ref={input => this.textInput = input} underlineColorAndroid={"transparent"} />; } else { mView = <TextInput {...this.props} ref={input => this.textInput = input} />; } return mView; } }
總結
基本實現思路是根據平臺的不同,呼叫平臺特有的屬性來統一顯示效果,再在使用的時候,外層巢狀 View 來實現統一樣式的底部邊框,還能新增類似密碼點選可見等效果。
今天10.24 程式員節了,祝各位節日快樂。
如果有什麼建議或者問題可以隨時聯絡我,共同探討學習: