RN的&&在文本輸入中的應(yīng)用

處理文本輸入

TextInput是一個允許用戶輸入文本的基礎(chǔ)組件。它有一個名為onChangeText的屬性,此屬性接受一個函數(shù),而此函數(shù)會在文本變化時被調(diào)用。
假如我們要實現(xiàn)當(dāng)用戶輸入時,實時將其以單詞為單位翻譯為另一種文字。我們假設(shè)這另一種文字來自某個吃貨星球,只有一個單詞: ??。所以"Hello there Bob"將會被翻譯為"??????"。

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

export default class PizzaTranslator extends Component {
  constructor(props) {
    super(props);
    this.state = {text: ''};
  }

  render() {
    return (
      <View style={{padding: 10}}>
        <TextInput
          style={{height: 40}}
          placeholder="Type here to translate!"
          onChangeText={(text) => this.setState({text})}
        />
        <Text style={{padding: 10, fontSize: 42}}>
          {this.state.text.split(' ').map((word) => word && '??').join(' ')}
        </Text>
      </View>
    );
  }
}

關(guān)于{this.state.text.split(' ').map((word) => word && '??').join(' ')}這段代碼,具體可以理解為,text文本先根據(jù)空格分隔成數(shù)組,再通過map方法遍歷,其中map((word)=>部分,word是遍歷數(shù)組的item,=>代表匿名函數(shù),&&則表示符號前的值不為空時,返回&&后的值,可以類似理解為java中的三元運算符相似的概念

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容