Je suis coincé dans une fonction apparemment simple. Comment puis-je obtenir une valeur (chaîne) à partir d'un TextInput?
Voici un extrait du code:
const Insert = props => { const [enteredName, setEnteredName] = useState(); const sendValues = (enteredName) => { console.log(enteredName); }; <TextInput placeholder="Your Name" blurOnSubmit autoCorrect={false} maxLength={30} autoCapitalized="words" placeholderTextColor="#777" value={enteredName} onChangeText={text => setEnteredSurname(text)} /> <View> <Button title="Submit" onPress={sendValues(enteredName)} />
J'obtiens la saisie lorsque je tape mais ce n'est pas le cas soumettre quoi que ce soit.
Une idée à ce sujet ??
Merci d'avance!
3 Réponses :
class AwesomeProject extends Component { constructor(props){ super(props) this.state = { username: '', password: '', } } _handlePress() { console.log(this.state.username); console.log(this.state.password); } render() { return ( <ScrollView style={styles.content}> <View style={styles.content}> <Text style={styles.welcome}> Create Account </Text> <Text style={styles.textStyle}> Name </Text> <TextInput style={styles.textInputStyle} placeholder="Enter Name" returnKeyLabel = {"next"} onChangeText={(text) => this.setState({username:text})} /> <Text style={styles.textStyle}> Name </Text> <TextInput style={styles.textInputStyle} placeholder="Enter Name" returnKeyLabel = {"next"} onChangeText={(text) => this.setState({password:text})} /> <Button onPress={() => this._handlePress()} style={styles.buttonStyle}> Submit </Button> </View> </ScrollView> ); } }
Vous devez transformer votre onPress d'une expression en une fonction et initialiser votre état
const Insert = props => { const [enteredName, setEnteredName] = useState(''); //INIT TO EMPTY function sendValues(enteredName) { console.log(enteredName); }; <TextInput placeholder="Your Name" blurOnSubmit autoCorrect={false} maxLength={30} autoCapitalized="words" placeholderTextColor="#777" value={enteredName} onChangeText={text => setEnteredSurname(text)} /> <View> <Button title="Submit" onPress={() => sendValues(enteredName)} /> //Function not expression </View>
Essayez ceci, vous devez l'utiliser comme ceci:
import React, { useState } from 'react'; import {Text, View,TextInput,Button} from 'react-native'; export default Example = () => { const [enteredName, setEnteredName] = useState(''); sendValues = (enteredName) =>{ console.log(enteredName); }; return ( <View> <Text>Hey</Text> <TextInput placeholder="Your Name" blurOnSubmit autoCorrect={false} maxLength={30} autoCapitalized="words" placeholderTextColor="#777" value={enteredName} onChangeText={text => setEnteredSurname(text)} /> <View> <Button title="Submit" onPress={() => sendValues(enteredName)} /> </View> </View> ); }