React Native學(xué)習(xí)組件之TextInput

Demo展示

RNTextInput.gif

搜索框自動(dòng)提示遗锣。此demo分為兩部分,第一是我們自定義輸入框迎吵,RN默認(rèn)的輸入框不是很美觀躲撰;第二個(gè)是自動(dòng)列表提示。demo比較簡(jiǎn)單击费,我們快速的來(lái)實(shí)現(xiàn)它吧拢蛋。

自定義輸入框

在根目錄上新建一個(gè)search.js文件

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

var onePT = 1 / PixelRatio.get();

class SearchComponent extends Component {

    render() {
        return (
            <View style={styles.flex}>
                <View style={[styles.inputHeight, styles.flexDirection]}>
                    <View style={[styles.flex, styles.input]}>
                        <TextInput
                            //這里表示輸入自帶的下劃線顏色透明
                            underlineColorAndroid={'transparent'}
                        />
                    </View>
                    <View style={styles.btn }>

                        <Text >搜索</Text>
                    </View>
                </View>

            </View>
        );
    }

}

const styles = StyleSheet.create({

    flex: {
        flex: 1
    },

    flexDirection: {
        flexDirection: 'row'
    },
    input: {
        borderWidth: 1,
        marginLeft: 5,
        paddingLeft: 5,
        borderColor: '#ccc',
        justifyContent: 'center',
        borderRadius: 4
    },
    inputHeight: {
        height: 45
    },
    btn: {
        width: 55,
        marginLeft: -5,
        marginRight: 5,
        backgroundColor: '#23beff',
        justifyContent: 'center',
        alignItems: 'center',
        borderBottomRightRadius: 4,
        borderTopRightRadius: 4
    },
    result: {

        marginLeft: 5,
        marginRight: 5,
        height: 200,
        borderColor: '#ccc',
        borderBottomWidth: 1,
        borderRightWidth: 1,
        borderLeftWidth: 1
    },
    resultItem: {
        fontSize: 16,
        paddingLeft: 10,
        paddingTop: 10,
        paddingBottom: 10,
        borderWidth: onePT,
        borderColor: '#ddd'

    },

    resultItemBottomLine: {
        borderBottomWidth: onePT,
        borderColor: '#ddd',
    }
});
module.exports = SearchComponent;

我們?cè)趇ndex.android.js文件里面使用它

import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View
} from 'react-native';

var SearchComponent = require('./search');

class RNTextInput extends Component {
    render() {
        return (
            <View style={[styles.flex, styles.topStatus]}>

                <SearchComponent/>

            </View>
        );
    }
}

const styles = StyleSheet.create({
    flex: {
        flex: 1
    },
    topStatus: {
        marginTop: 25
    }
});

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

效果如下:

serach_1.png

自動(dòng)提示列表

  • TextInput常用屬性

    • returnKeyType

      因?yàn)檫@里的使用場(chǎng)景是搜索,所我們虛擬鍵盤的返回鍵是search

    • placeholder

      顯示在輸入前的占位符蔫巩,如“請(qǐng)輸入關(guān)鍵字”谆棱。有點(diǎn)像Android中EditText中的hint提示

    • value

      通過(guò)this.state.value修改TextInput的value的變化

    • onEndEditing

      用戶結(jié)束編輯時(shí)觸發(fā)該事件,會(huì)將this.state.value寫入圆仔。這樣垃瞧,就能在搜索框中顯示該值

    • onChangeText

      監(jiān)聽(tīng)輸入框值的變化,onChangeText獲取的值作為字符串傳入

  • 代碼實(shí)現(xiàn)

在serach.js文件添加一些代碼

...

var onePT = 1 / PixelRatio.get();

class SearchComponent extends Component {

    //我們可以在構(gòu)造方法中進(jìn)行初始化
    constructor(props) {
        super(props);
        this.state = {
            show: false,
        };
    }

    /**
     * 顯示搜索結(jié)果
     * @param result
     */
    showResult(result) {
        var result = result;
        this.setState({
            show: true,
            value: result
        });
    }

    /**
     * 隱藏搜索結(jié)果
     * @param result
     */
    hideResult(result) {
        this.setState({
            show: false,
            value: result
        });
    }   
    render() {
        return (
            <View style={styles.flex}>
                <View style={[styles.inputHeight, styles.flexDirection]}>
                    <View style={[styles.flex, styles.input]}>
                        <TextInput
                            underlineColorAndroid={'transparent'}
                            returnKeyType="search"
                            placeholder="請(qǐng)輸入關(guān)鍵字"
                            onChangeText={(text)=>this.showResult(text)}
                            value={this.state.value}
                            onEndEditing={(text)=>this.hideResult({text})}
                        />
                    </View>
                    <View style={styles.btn }>

                        <Text onPress={()=>this.hideResult(this.state.value)}>搜索</Text>
                    </View>
                </View>

                { this.state.show ?
                    <View style={styles.result}>
                        <View style={[styles.resultItemBottomLine, styles.flex]}>
                            <Text style={[styles.resultItem]}
                                  numberOfLines={1}
                                  onPress={this.hideResult.bind(this, this.state.value + '超市')}>
                                {this.state.value}超市
                            </Text>
                        </View>

                        <View style={[styles.resultItemBottomLine, styles.flex]}>
                            <Text style={styles.resultItem}
                                  numberOfLines={1}
                                  onPress={this.hideResult.bind(this, this.state.value + '道路')}>
                                {this.state.value}道路
                            </Text>
                        </View>

                        <View style={[styles.resultItemBottomLine, styles.flex]}>
                            <Text style={[styles.resultItem]}
                                  numberOfLines={1}
                                  onPress={this.hideResult.bind(this, this.state.value + '綜合商店')}>
                                {this.state.value}綜合商店
                            </Text>
                        </View>

                        <View style={[styles.resultItemBottomLine, styles.flex]}>
                            <Text style={[styles.resultItem]}
                                  numberOfLines={1}
                                  onPress={this.hideResult.bind(this, this.state.value + '醫(yī)院')}>
                                {this.state.value}醫(yī)院
                            </Text>
                        </View>

                        <View style={[styles.flex]}>
                            <Text style={[styles.resultItem]}
                                  numberOfLines={1}
                                  onPress={this.hideResult.bind(this, this.state.value + '美容院')}>
                                {this.state.value}美容院
                            </Text>
                        </View>
                    </View>
                    : null
                }
            </View>
        );
    }

}

... 

運(yùn)行效果如下:

search_2.png

總結(jié)

我們通過(guò)判斷this.state.show來(lái)確定是否顯示結(jié)果列表坪郭。如果this.state.show是true个从,則顯示。如果是false,則隱藏(null對(duì)象不顯示)嗦锐。

結(jié)果列表的規(guī)則是:輸入關(guān)鍵字+預(yù)設(shè)關(guān)鍵字鸵隧。這是我們模擬服務(wù)端傳過(guò)來(lái)的數(shù)據(jù)。同時(shí)意推,點(diǎn)擊結(jié)果列表中的某一項(xiàng)豆瘫,應(yīng)該隱藏列表并且將結(jié)果顯示在輸入框中。onPress={this.hideResult.bind(this, this.state.value + '超市')}就是當(dāng)用戶點(diǎn)擊時(shí)菊值,將字符傳結(jié)果輸入的到hide方法中外驱。在js中,調(diào)用有參數(shù)的方法腻窒,我們可以使用bind方法來(lái)傳參昵宇。

hide方法很簡(jiǎn)單,就是將this.state.show設(shè)置為false儿子,這樣會(huì)將結(jié)果列表隱藏起來(lái)了瓦哎。因?yàn)闋顟B(tài)的改變引起了視圖的重新渲染,遇到this.state.show為false柔逼,就不渲染結(jié)果列表了蒋譬。

好了,我們的TextInput組件就學(xué)習(xí)完了愉适,若有不對(duì)之處犯助,還請(qǐng)告知。謝謝维咸!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末剂买,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子癌蓖,更是在濱河造成了極大的恐慌瞬哼,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,427評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件租副,死亡現(xiàn)場(chǎng)離奇詭異坐慰,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)附井,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門讨越,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人永毅,你說(shuō)我怎么就攤上這事∪斯” “怎么了沼死?”我有些...
    開(kāi)封第一講書人閱讀 165,747評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)崔赌。 經(jīng)常有香客問(wèn)我意蛀,道長(zhǎng)耸别,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,939評(píng)論 1 295
  • 正文 為了忘掉前任县钥,我火速辦了婚禮秀姐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘若贮。我一直安慰自己省有,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布谴麦。 她就那樣靜靜地躺著蠢沿,像睡著了一般。 火紅的嫁衣襯著肌膚如雪匾效。 梳的紋絲不亂的頭發(fā)上舷蟀,一...
    開(kāi)封第一講書人閱讀 51,737評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音面哼,去河邊找鬼野宜。 笑死,一個(gè)胖子當(dāng)著我的面吹牛魔策,可吹牛的內(nèi)容都是我干的速缨。 我是一名探鬼主播,決...
    沈念sama閱讀 40,448評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼代乃,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼旬牲!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起搁吓,我...
    開(kāi)封第一講書人閱讀 39,352評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤原茅,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后堕仔,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體擂橘,經(jīng)...
    沈念sama閱讀 45,834評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評(píng)論 3 338
  • 正文 我和宋清朗相戀三年摩骨,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了通贞。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,133評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡恼五,死狀恐怖昌罩,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情灾馒,我是刑警寧澤茎用,帶...
    沈念sama閱讀 35,815評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響轨功,放射性物質(zhì)發(fā)生泄漏旭斥。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評(píng)論 3 331
  • 文/蒙蒙 一古涧、第九天 我趴在偏房一處隱蔽的房頂上張望垂券。 院中可真熱鬧,春花似錦羡滑、人聲如沸菇爪。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,022評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)娄帖。三九已至,卻和暖如春昙楚,著一層夾襖步出監(jiān)牢的瞬間近速,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,147評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工堪旧, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留削葱,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,398評(píng)論 3 373
  • 正文 我出身青樓淳梦,卻偏偏與公主長(zhǎng)得像析砸,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子爆袍,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容