基础篇章:React Native 之 TextInput 的讲解
TextInput 是一个允许用户输入文本的基础组件。它有一个onChangeText的属性,该属性接受一个函数,每当文本输入发生变化时,此函数就会被调用。它还有一个onSubmitEditing的属性,当文本输入完被提交的时候调用。 官网例子import React,{ Component } from 'react';
import { AppRegistry,Text,TextInput,View } from 'react-native';
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);
这个例子实现的功能就是当我们在文本输入框里输入一个单词时,该单词就会换成??,如果输入的是一句话或者很多单词,就会实时动态的把一句话拆成以一个一个的单词,然后替换成??。比如:”Hello there Bob”将会被翻译为”??????”。 解释如果你们不懂js的话,可能看着有点困难,所以学React Native的时候,大家最好先去看看js,至少得懂一些。 再说一遍,以后就不解释了,不懂js语法的自行去学习。 属性方法
TextInput实践效果图废话不多说,结合我们之前学的一些基础,再加上TextInput的知识,我们现在练习一个demo,巩固一下以前的知识点。效果图如下: demo代码import React,{ Component } from 'react';
import {
AppRegistry,StyleSheet,View,TextInput
} from 'react-native';
class TextInputDemo extends Component {
render() {
return (
<View style={styles.container}> <View style={styles.top_half_view}> <View style={styles.title_view}> <Text style={styles.title_text}> 邮箱登录 </Text> </View> <TextInput style={styles.textinput} placeholder='邮箱' numberOfLines={1} autoFocus={true} underlineColorAndroid={'#e1e1e1'} /> <TextInput style={styles.textinput} placeholder='密码' numberOfLines={1} secureTextEntry={true} underlineColorAndroid={'#e1e1e1'} /> <View style={{backgroundColor:'#ffffff',flexDirection:'row',alignItems:'center',justifyContent:'center'}}> <View style={styles.style_view_register}> <Text style={{color:'#5ac4ef'}}> 注册 </Text> </View> <View style={styles.style_view_login}> <Text style={{color:'white'}}> 登录 </Text> </View> </View> <Text style={styles.bottom_text}> 忘了密码?点此找回 </Text> </View> <View style={styles.bottom_half_view}> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1,backgroundColor: 'white',},title_view:{ flexDirection:'row',height:50,alignItems: 'center',backgroundColor:'#27b5ee',title_text:{ color:'white',fontSize:22,marginLeft:20,textAlign:'center' },top_half_view:{ flex: 1.3,bottom_half_view:{ flex: 1,backgroundColor: '#eeeeee',textinput: { backgroundColor:'#fff',marginTop:5,marginRight:20,textAlign:'left',style_view_login:{ flex:1,marginTop:20,height:35,borderRadius:5,justifyContent: 'center',style_view_register:{ flex:1,borderColor:'#5ac4ef',borderWidth: 1,bottom_text:{ color:'#27b5ee',fontSize:14,marginTop:10,fontWeight:'bold' },}); AppRegistry.registerComponent('TextInputDemo',() => TextInputDemo);
到这里关于TextInput的知识点我们就讲的差不多了,希望大家亲自实践去实现一下上面的例子,肯定会收获很多,想学更多开发知识,欢迎大家关注微信公众号:非著名程序员(smart_android)。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |