admin管理员组

文章数量:1404557

I have two buttons in my Parent ponent AddRow and DeleteRow buttons if i click on addRow button it will add an empty row in grid and if i click deleteRow button it will delete selected rows from grid. I have added two functions for adding row to grid and removing record from grid in my child ponent. How to call these functions from parent ponent button click events. Similar sample code given below.

i have used lift up state to parent ponent it is working is any other way to do it because i need to move entire child ponent code to parent ponent and there are 4 child ponents lifting the all the child code to parent bees huge code in parent ponent what is the react way doing things in this situation.

import { render } from 'react-dom';
import React, { useState } from 'react';
    
const App = () => {
  return (
    <Parent />
  );
};
    
const Parent = () => { 
  return (
    <div>
      <h1>Parent Component</h1>
      <div id="newElements"></div>
      <input type="button" value="Add New Element" onClick={} />
      <input type="button" value="Clear Elements" onClick={} />  
      <Child />
    </div>
  )
};
    
const Child = () =>{  
  function addElement() {
    // this function will add row to grid.
    var node = document.createElement("h1");  

    node.innerHTML="New Element";
    document.getElementById('newElements').appendChild(node); 
  }

  function clearElement() {
    // this function will remove row from grid
    document.getElementById('newElements').innerHTML=""; 
  }

  return (
    <div>
      <h1>Child Component</h1>
        // here the grid will be there in my actual code 
        <div id="newElements"></div>
      </div>
  )
};

render(<App />, document.getElementById('root'));

I need to call addElement() function when click on parent ponents AddNewElement button.

本文标签: javascriptHow to pass down event from parent to child in react with functional componentsStack Overflow