-
TextInput
是一個允許用戶輸入文本的基礎組件。它有一個名為onChangeText的屬性,此屬性接受一個函數(shù)锐秦,而此函數(shù)會在文本變化時被調用。另外還有一個名為onSubmitEditing的屬性那先,會在文本被提交后(用戶按下軟鍵盤上的提交鍵)調用农猬。
- 假如我們要實現(xiàn)當用戶輸入時,實時將其以單詞為單位翻譯為另一種文字售淡。我們假設這另一種文字來自某個吃貨星球斤葱,只有一個單詞: ??慷垮。所以"Hello there Bob"將會被翻譯為"??????"。
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput
} from 'react-native';
export default class DTest 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>
);
}
}
// 注冊應用(registerComponent)后才能正確渲染
// 注意:只把應用作為一個整體注冊一次揍堕,而不是每個組件/模塊都注冊
AppRegistry.registerComponent('DTest', () => DTest);
- 在上面的例子里料身,我們把text保存到state中,因為它會隨著時間變化衩茸。
- 文本輸入方面還有很多其他的東西要處理芹血。比如你可能想要在用戶輸入的時候進行驗證,在React的表單組件中的受限組件一節(jié)中有一些詳細的示例(注意react中的onChange對應的是rn中的onChangeText)楞慈。此外你還需要看看TextInput的文檔幔烛。
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者