In React, components manage their own state. In this lesson, we‘ll walk through building a component which manages it‘s own state as well as using TextInput and TouchableHighlight to handle touch events.
import React, { Component, PropTypes } from ‘react‘; import { View, Text, StyleSheet, TextInput, TouchableHighlight, ActivityIndicatorIOS } from ‘react-native‘; var style = StyleSheet.create({ mainContainer: { flex: 1, padding: 30, marginTop: 65, flexDirection: ‘column‘, justifyContent: ‘center‘, backgroundColor: ‘#48BBEC‘ }, title: { marginBottom: 20, fontSize: 25, textAlign: ‘center‘, color: ‘#fff‘ }, searchInput: { height: 50, padding: 4, marginRight: 5, fontSize: 23, borderWidth: 1, borderColor: ‘white‘, borderRadius: 8, color: ‘white‘ }, buttonText: { fontSize: 18, color: ‘#111‘, alignSelf: ‘center‘ }, button: { height: 45, flexDirection: ‘row‘, backgroundColor:‘white‘, borderColor:‘white‘, borderWidth:1, borderRadius:8, marginBottom:10, alignSelf:‘stretch‘, justifyContent:‘center‘ } }); export default class Main extends Component{ constructor(props){ super(props) this.state = { username: ‘‘, isLoading: false, error: false }; } handleChange(event){ this.setState({ username: event.nativeEvent.text }) } handleSubmit(event){ //update our indicatorIOS spinner this.setState({ isLoading: true }); console.log(‘submit‘, this.state.username); //fetch data from github //reroute to the next passing that github informaiton } render(){ return ( <View style={style.mainContainer}> <Text style={style.title}>Search for a Github User</Text> <TextInput style={style.searchInput} value={this.state.username} onChange={this.handleChange.bind(this)} /> <TouchableHighlight style={style.button} onPress={this.handleSubmit.bind(this)} underlayColor="white" > <Text style={style.buttonText}>SEARCH USER</Text> </TouchableHighlight> </View> ) } }
<TextInput style={style.searchInput} value={this.state.username} onChange={this.handleChange.bind(this)} />
Search box, once value changed, set current username state.
<TouchableHighlight style={style.button} onPress={this.handleSubmit.bind(this)} underlayColor="white" >
Search button, a touch button, so not onClick event but onPress event.
underlayColor: When touch, change background color to white color.
时间: 2024-10-05 12:58:07