javascript - Los argumentos dentro de "onChange" no son compatibles con "NativeSyntheticEvent"
Soy nuevo en React Native y cuando intento hacer esto
<TextInput
style={styles.input}
onChange={(text) => setPontoValue(text)}
/>
recibo este error
TS2345: Argument of type 'NativeSyntheticEvent<TextInputChangeEventData>' is not assignable to parameter of type 'SetStateAction<undefined>'. Type 'NativeSyntheticEvent<TextInputChangeEventData>' provides no match for the signature '(prevState: undefined): undefined'.todo el código está abajo
import React, { useState } from 'react'
import {
TextInput,
TouchableOpacity,
StyleSheet,
SafeAreaView,
Text,
View, Button,
} from 'react-native'
export default function App() {
const [pontoValue, setPontoValue] = useState()
const [dataValue, setDataValue] = useState()
return (
<SafeAreaView style={styles.container}>
<View style={styles.repositoryContainer}>
<TextInput
style={styles.input}
onChange={(text) => setPontoValue(text)}
/>
<TextInput
style={styles.input}
value={dataValue}
/>
<TouchableOpacity>
<Button
title="Calcular"
onPress={teste}>Converter
</Button>
</TouchableOpacity>
</View>
</SafeAreaView>
)
function teste() {
if (pontoValue) {
setDataValue(pontoValue.replace(/[ .]+/g, ''))
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignContent: 'center',
backgroundColor: '#7199c1',
},
repositoryContainer: {
marginBottom: 15,
marginHorizontal: 15,
backgroundColor: '#fff',
padding: 20,
},
input: {
height: 40,
padding: 5,
borderColor: 'gray',
borderWidth: 1,
},
buttonText: {
marginVertical: 11,
fontSize: 14,
fontWeight: 'bold',
color: '#fff',
backgroundColor: '#7159c1',
padding: 15,
},
})
Respuesta #1
El evento onChange devuelve un objeto de evento que tiene la función nativeEvent, la cual proporciona acceso a las siguientes propiedades: { eventCount, target, text }
necesitas la propiedad text, así que puedes usar:
onChange={(event) => setPontoValue(event.nativeEvent.text)}
o
onChangeText={(text) => setPontoValue(text)}
Respuesta #2
Te sugiero que uses la propiedad onChangeText.
onChangeText es una propiedad que te da solo los cambios de texto.
onChange, por otro lado, pasa un evento.
Entonces, prueba esto
<TextInput
style={styles.input}
onChangeText={(text) => setPontoValue(text)}
/>
Además, siempre inicializa tus variables de estado.
const [pontoValue, setPontoValue] = useState('')
const [dataValue, setDataValue] = useState('')
Reducirá la probabilidad de obtener errores undefined.
Espero que funcione.
