Estoy tratando de mostrar el estado del componente secundario en el componente principal, pero de alguna manera el texto "abcde" aún no se muestra, aquí está el código de muestra
import React from 'react'; import {SafeAreaView, StyleSheet, Text} from 'react-native'; import {TouchableOpacity} from 'react-native-ui-lib'; class ChidComponent extends React.Component { constructor(props) { super(props); this.state = { text: '', }; } render() { return ( <SafeAreaView> <TouchableOpacity onPress={() => { this.setState({text: 'abcde'}); this.props.getText(this.state.text); }}> <Text>Get Text</Text> </TouchableOpacity> </SafeAreaView> ); } } const style = StyleSheet.create({ text: { fontWeight: 'bold', fontSize: 40, }, }); class ParentComponent extends React.Component { constructor(props) { super(props); this.state = { text: '', }; } getTextFromChild(value) { this.setState({text: value}); } render() { return ( <SafeAreaView> <Text>{this.state.text}</Text> <ChidComponent getText={this.getTextFromChild.bind(this)} press={() => this.setState({show: !this.state.show})} textStyle={style.text} /> </SafeAreaView> ); } } export default ParentComponent;
Pero de alguna manera la pantalla todavía está vacía, el 'abcde' aún hasta que hago clic dos veces , proviene de un componente funcional, así que no sé qué está pasando, por favor ayuda, muchas gracias.
Su método getTextFromChild
en ParentComponent
está eliminando la propiedad show
del estado, actualícelo a esto:
getTextFromChild(value) { this.setState({text: value, show: true }); }
EDITAR: setState
es asíncrono, puede pasar una función de devolución de llamada como argumento para acceder al estado actualizado.
<TouchableOpacity onPress={() => { this.setState({text: 'abcde'}, () => { this.props.getText(this.state.text); }); }}>
Deberia trabajar.