I am trying to send a variable data from my child class to my parent class.
Doubts
- My child is a functional component as a .js file and my parent is a class component as a .tsx file.
(was wondering if this would be an issue)
App.Component(.Tsx file)
I've updated my App component with state to pass to child
import React from "react";
import FieldData from "./FieldData";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
childData: "this is the input for now"
};
this.handleData = this.handleData.bind(this);
}
handleData(dataValue) {
this.setState({ data: dataValue });
};
render() {
return (
<div>
Hello passing data from child to parent
{/* Want to overwrite "this.state.childData" with data from child class */}
<FieldData handleData ={this.handleData } />
here is output {this.state.childData}
</div>
);
}
}
export default App;
I've updated the parent class. But I am not sure what to do in the child class.
I am not sure how to set the constructor or call the props in a function component. I understand that we cannot set constructor in stateless function component. (I am able to do so if the child is a class component). But I am using hooks, is the reason why I am using function child.
Sample Child functional component(.js file)
I have a function in the child class that print out json object array. I want to pass this "convertedData" value back to the parent class.
const PriceTotal = ({ control }) => {
const test = useWatch({
control,
name: `items`
});
if (test) {
const convertedData = test.map((element) => {
Object.keys(element).forEach((key) => {
// check value is exist and parse value string to int
if (element[key].value)
element[key].value = parseFloat(element[key].value);
});
return element;
});
console.log(convertedData);
// Want to send convertedData back to parent
}
return null;
};
I provided a sandbox Below
Sandbox
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…