Finalmente llegué a un punto en el que ya no puedo entenderlo. Mi objetivo es bastante simple. Tengo un campo de entrada en un componente nativo de reacción.
Quiero guardar el valor del texto de entrada en el estado redux (más adelante). Pero, siempre me queda indefinido en e.target.value. Este problema se ha publicado millones de veces y probé muchas soluciones. Ninguno de ellos funcionó. Supongo que me estoy perdiendo algo más.
Por cierto. El botón es solo para obtener el estado más reciente en el registro.
Este es mi componente:
import React, { Component } from 'react'; import { Button, StyleSheet, TextInput, View } from 'react-native'; import allActions from '../../actions/allActions'; import { useDispatch, useSelector } from 'react-redux'; import store from '../../store'; const styles = StyleSheet.create({ input: { height: 40, marginTop: 20, borderWidth: 1, borderColor: '#d3d3d3', padding: 10, } }); class Name extends Component { constructor(props) { super(props); this.state = { user: "" }; this.handleChange = this.handleChange.bind(this); this.getMyState = this.getMyState.bind(this); } handleChange(event) { event.preventDefault(); this.setState({ user: event.target.value }); } getMyState(event) { event.preventDefault(); console.log(this.state.user); } render() { return ( < View > < TextInput style = { styles.input } onChange = { this.handleChange } /> < Button title = { 'get log' } onPress = { this.getMyState } /> < /View> ); } } export default Name;Use onChangeText en lugar de onChange así:
const myInputFunction(text: string) { if (/* check whatever you want */) { this.setState({inputText: text}) } } <TextInput value={this.state.inputText} maxLength={1} onSubmitEditing={this.textHandler} onChangeText={(text) => myInputFunction(text)} // Not sure if you have to write this.function here I am using React State hooks and functional components instead of classes /> ´´´Para cualquiera que esté luchando con esto, aquí está la solución que se me ocurrió. Gracias a @Maximilian Dietel me di cuenta de mi problema inicial usando onChange en lugar de onChangeText. Después de eso, cambié el componente de clase a un componente funcional para poder usar mis ganchos para guardar el nuevo estado en redux.
import React, {Component} from 'react'; import {Button, StyleSheet, Text, TextInput, View} from 'react-native'; import allActions from '../../actions/allActions'; import {useDispatch, useSelector} from 'react-redux'; import store from '../../store'; const styles = StyleSheet.create({ input: { height: 40, marginTop: 20, borderWidth: 1, borderColor: '#d3d3d3', padding: 10, } }); function Name (props) { const dispatch = useDispatch(); /** * Save the new user to the state * @param text */ const handleChange = (text) => { dispatch(allActions.userActions.setUser(text)); } return ( <View> <TextInput style={styles.input} defaultValue={store.getState().user.user} onChangeText={handleChange} /> </View> ); } export default Name;