0
I have a modal (child) component that I want to display information by clicking on the parent component object.
Son:
import React, {Component} from 'react';
import {Modal, Text, View, Button} from 'react-native';
export default class ModalExample extends Component {
render() {
return (
<View>
<Modal
animationType="slide"
transparent={false}
visible={this.props.modalVisible}
onRequestClose={() => {
showModal(!this.props.modalVisible);
}}>
<Text>Estou Funcionando!</Text>
<Button
color = "#b0bec5"
title="Sair"
onPress={() => {
showModal(!this.props.modalVisible);
}}
/>
</Modal>
</View>
)
}
}
Father:
import React, { Component } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Modal, Button } from 'react-native';
import ModalDescriptions, { setModalVisible } from './commons/modalDescriptions';
import api from '../service/api';
export default class budgetList extends Component {
constructor(props) {
super(props);
this.state = {
budgetlist: [],
modalVisible: false,
};
}
async componentDidMount(){
await api.get()
.then(res => {this.setState({ budgetlist: res.data })});
}
showModal(visible) {
this.setState({ modalVisible: visible })
}
handleDescription = (i) => {
const data = this.state.budgetlist;
this.setState({ desc: data[i].description });
};
renderItem = ({ item, index }) => (
<View style={styles.card}>
<TouchableOpacity onPress={() => {
this.showModal(true);
this.handleDescription(index);
}}>
<View style={styles.entrace}>
<Text style={styles.customer}>{item.customer}</Text>
<Text style={styles.value}>{item.value}</Text>
</View>
<Text style={styles.seller}>Vendedor: {item.seller}</Text>
</TouchableOpacity>
</View>
);
render() {
return (
<View>
<FlatList
keyExtractor={budgetlist => budgetlist.id.toString()}
data={this.state.budgetlist}
renderItem={this.renderItem}
/>
<ModalDescriptions />
</View>
)
}
}
By clicking on the parent component item I can display the modal, but by clicking the Exit button it says which function modalVisible
is undefined
.
I am learning React and I understand that this is happening because it is not possible to change the state of the parent component, but how can I solve this?
Dude, I don’t know much about React because I only worked with Vue.js, but in these cases the child component emits an event and the parent component listens to this event... when the event occurs the parent component changes its own state.
– fernandosavio
You want the child component to trigger a function in the parent component?
– Maycon F. Castro
That, and changing the state of the parent component... that is correct or not a good practice?
– felipenoka