最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass down event from parent to child in react with functional components? - Stack Overflow

programmeradmin4浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论