處理文本輸入
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中的三元運算符相似的概念