美文网首页React Native
React Native--处理文本输入

React Native--处理文本输入

作者: 清风灬慕竹 | 来源:发表于2017-05-31 23:05 被阅读19次

看到React Native 中的文本输入 ,相信有人会有种感觉Text Input。对的,在React Native可以通过TextInput进行用户界面的文本输入。

TextInput是一个允许用户输入文本的基础组件。其中有一个属性onChangeText,可以接受一个函数,此函数会在文本变化时被调用。

其中一个属性onSubmitEditing,会在文本被提交后(用户按下软键盘上的提交键)调用。

假如我们要实现当用户输入时,实时将其以单词为单位翻译为另一种文字。我们假设这另一种文字来自某个吃货星球,只有一个单词: 🍕。所以"Hello there Bob"将会被翻译为"🍕🍕🍕"。

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
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>
);
}
}

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

在上面的例子里,我们把text保存到state中,因为它会随着时间变化。即通过onChangeText={(text) => this.setState({text})}来进行实现的。
其中text.split(' ')根据空格进行分割;map((word) => word && '🍕')合成一个数组,然后把每个数组元素转换为🍕;
join(' ')并在每个数组元素后面加空格。

相关文章

网友评论

    本文标题:React Native--处理文本输入

    本文链接:https://www.haomeiwen.com/subject/vzfsfxtx.html