importReact,{Component}from'react';import{AppRegistry,Text,StyleSheet}from'react-native';classTextInANestextendsComponent{constructor(props){super(props);this.state={titleText:"Bird's Nestaaa",bodyText:'This is not really a bird nest.'};}render(){return(<Textstyle={styles.baseText}><Textstyle={styles.titleText}onPress={this.onPressTitle}>{this.state.titleText}{'\n'}{'\n'}</Text><TextnumberOfLines={5}>{this.state.bodyText}</Text></Text>);}}conststyles=StyleSheet.create({baseText:{fontFamily:'Cochin',},titleText:{fontSize:20,fontWeight:'bold',},});// App registration and renderingAppRegistry.registerComponent('TextInANest',()=>TextInANest);
处理文本输入
TextInput是一个基本组件,允许用户输入文本。 它有一个onChangeText prop,它接受一个函数,每次文本改变时被调用,和一个onSubmitEditing prop,当一个函数被提交时被调用。
例如,让我们说,当用户键入时,您将他们的词翻译成不同的语言。 在这种新语言中,每个单词的写法都是一样的:🍕。 所以句子“Hello there Bob”将翻译为“🍕🍕🍕”。
1234567891011121314151617181920212223242526
importReact,{Component}from'react';import{AppRegistry,Text,TextInput,View}from'react-native';classPizzaTranslatorextendsComponent{constructor(props){super(props);this.state={text:''};}render(){return(<Viewstyle=><TextInputstyle=placeholder="Type here to translate!"onChangeText={(text)=>this.setState({text})}/><Textstyle=>{this.state.text.split(' ').map((word)=>word&&'🍕').join(' ')}</Text></View>);}}AppRegistry.registerComponent('PizzaTranslator',()=>PizzaTranslator);
<Text><Text>First part and </Text><Text>second part</Text></Text>// Text container: all the text flows as if it was one
// |First part |
// |and second |
// |part |
<View><Text>First part and </Text><Text>second part</Text></View>// View container: each text is its own block
// |First part |
// |and |
// |second part|
<View><MyAppText>Text styled with the default font for the entire application</MyAppText><MyAppHeaderText>Text styled as a header</MyAppHeaderText></View>