¿Podría decirme cómo obtener el valor del input field
o, en otras palabras, el valor del campo de entrada de nombre de usuario y contraseña al hacer clic en el botón?
aquí está mi código https://rnplay.org/apps/drT9vw
import React from 'react'; import { registerComponent, } from 'react-native-playground'; import { Text, View, Image, StyleSheet, TextInput, TouchableHighlight } from 'react-native'; class App extends React.Component { constructor(props){ super(props); this.state ={ userName :'', password:'' }; } login(){ alert(this.state.userName) } OnChangesValue(e){ console.log(e.nativeEvent.text); this.setState({ userName :e.nativeEvent.text, }) } changePassword(e){ console.log(e.nativeEvent.text); this.setState({ password :e.nativeEvent.text, }) } render() { return ( <View style={styles.container}> <Text style={styles.heading}> Login</Text> <TextInput style={styles.loginInput} onChange={(text)=> this.setState({userName:text})} ref="myInput" underlineColorAndroid='transparent' placeholder="username !" /> <TextInput style={styles.loginInput} ref="pass" onChange={this.changePassword.bind(this)} underlineColorAndroid='transparent' placeholder="password to ff!" secureTextEntry={true} /> <TouchableHighlight style={styles.touchable} onPress={this.login.bind(this)}> <Text style={styles.touchableButton}>Click</Text> </TouchableHighlight> </View> ) } } const styles = StyleSheet.create({ container: { backgroundColor: '#EF501E', flex: 1, alignItems: 'center', padding :20 }, logo: { width: 50, height: 50 }, heading: { fontSize: 30, marginTop: 20 }, loginInput: { height: 50, alignSelf: 'stretch', borderWidth: 1, borderColor: '#33090C', flexDirection: 'row', justifyContent: 'center', marginBottom:10 }, touchable:{ backgroundColor:'#2E18DD', height:40, alignSelf:'stretch', alignItems:'center', justifyContent:'center' }, touchableButton:{ color:'#fff', fontSize:10 } }); registerComponent(App);
actualizar
login(){ alert(this.refs.myInput.value) }
da indefinido
Al no obtener el problema exacto, está almacenando el nombre de usuario y la contraseña en la variable de estado. Entonces puede obtener los valores por this.state.userName
y this.state.password
. o puede usar las referencias también para obtener un valor como este: this.refs.myInput.value
.
Cambia esta diversión:
changePassword(text){ console.log(text); this.setState({ password :text, }) }
Consulte el mismo ejemplo en tutorialspoint: https://www.tutorialspoint.com/react_native/react_native_text_input.htm
Se puede hacer de dos maneras. Si los campos de entrada están controlados, puede obtener los valores del propio estado. En el caso de campos de entrada no controlados (su caso), puede usar refs para obtener los valores de entrada
login() { console.log(this.refs.myInput.value) }