Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

javascript - Reactjs sending data back from child function component to parent class component

I am trying to send a variable data from my child class to my parent class.

Doubts

  1. 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...