简体   繁体   English

如何将事件从父级传递给子级以与功能组件发生反应?

[英]How to pass down event from parent to child in react with functional components?

I have two buttons in my Parent component 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.我的父组件中有两个按钮 AddRow 和 DeleteRow 按钮,如果我单击 addRow 按钮,它将在网格中添加一个空行,如果我单击 deleteRow 按钮,它将从网格中删除选定的行。 I have added two functions for adding row to grid and removing record from grid in my child component.我在我的子组件中添加了两个函数,用于向网格添加行和从网格中删除记录。 How to call these functions from parent component button click events.如何从父组件按钮点击事件中调用这些函数。 Similar sample code given below.下面给出了类似的示例代码。

i have used lift up state to parent component it is working is any other way to do it because i need to move entire child component code to parent component and there are 4 child components lifting the all the child code to parent becomes huge code in parent component what is the react way doing things in this situation.我已经使用提升 state 到父组件它正在工作是任何其他方式来做到这一点,因为我需要将整个子组件代码移动到父组件并且有 4 个子组件将所有子代码提升到父级成为父级中的巨大代码组件在这种情况下做事的反应方式是什么。

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 components AddNewElement button.单击父组件 AddNewElement 按钮时,我需要调用 addElement() function。

You should lift your state up . 你应该提高自己的状态 Move the functions and state to parent and pass it down via props . functionsstate移到父级,然后通过props传递给父级。 Remember, React is all about data flowing down the component's tree, never up. 记住,React是关于数据流向组件树的,而不是流向树的。

import { render } from 'react-dom';
import React, { useState } from 'react';

const App = () => {
  return (
    <Parent />
  );
};

const Parent = () =>{ 
    const addElement = () =>
    {
      //this function will add row to grid.
      var node = document.createElement("h1");  
      node.innerHTML="New Element";
      document.getElementById('newElements').appendChild(node); 
    }
    const clearElement = () =>
    {
      //this function will remove row from grid
      document.getElementById('newElements').innerHTML=""; 
    }
  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 add={addElement} clear={clearElement}/>
  </div>
)

};

const Child = ({add, clear}) =>{ 

  return (
  <div>
    <h1>Child Component</h1>
    <button onClick={add}>Add</button>
    <button onClick={clear}>Clear</button>
    <div id="newElements"></div>
  </div>)
};
render(<App />, document.getElementById('root'));

If I was to say what is THE react way to do it, it would be something like this:如果我要说什么是反应方式来做到这一点,它会是这样的:

Parent component:父组件:

export default function App() {
  const [rows, setRows] = React.useState([]);

  const addElement = () => {
    setRows([...rows, "New Element"]);
  };

  const clearElement = () => {
    setRows((prevState) => {
      const arr = [...prevState];
      arr.splice(-1);
      return arr;
    });
  };

  return (
    <div>
      <h1>Parent Component</h1>
      <input type="button" value="Add New Element" onClick={addElement} />
      <input type="button" value="Clear Element" onClick={clearElement} />
      <Child rows={rows} />
    </div>
  );
}

Child component:子组件:

const Child = (props) => {
  return (
    <div>
      <h1>Child Component</h1>
      {props.rows.map((row, index) => {
        return <h1 key={index}>{row}</h1>;
      })}
    </div>
  );
};

One of the main points in using react is to skip dynamic rendering to some arbitrary point in the application (like id="uniqueIdHere" ), doesn't matter if you use jQuery or new JS syntax to target it and then mutate JS.使用 react 的要点之一是将动态渲染跳过到应用程序中的任意点(如id="uniqueIdHere" ),无论您是使用 jQuery 还是新的 JS 语法来定位它然后改变 JS。 If React is used properly, it will make sure to only re-render changing nodes (shadow DOM) and will keep track of the state (how many nodes there should be at any point in time) appropriately.如果 React 使用得当,它将确保只重新渲染变化的节点(影子 DOM)并适当地跟踪状态(在任何时间点应该有多少节点)。

As you can see the logic to render new nodes or remove them, isn't really that big and scary when using react in a way that it was built to be used.正如您所看到的渲染新节点或删除它们的逻辑,当以某种方式使用 React 时,它并没有那么大和可怕。

Here's a sandbox to play around, happy to answer any questions you have about the code I wrote.这是一个可以玩的沙箱,很高兴回答您对我编写的代码的任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 React 中将事件从子组件传递到父组件返回到另一个子组件 - how to pass an event from a child component to parent component back down to another child in React 在 React 中将功能组件从子组件传递给父组件 - Pass functional component from child to parent in React 如何在 React.js 功能组件中将子组件 state 传递给父组件 state? - How to pass child component state to parent component state in React.js functional components? 使用功能组件从父级清除 React 子级输入值 - Clear React child input value from parent using functional components 通过 React 功能组件将 function 从父级传递给子级 - Passing down function from parent to child through React functional component 如何在Reactjs中将道具从父组件传递到子组件 - How to pass props from parent components to child components in reactjs 如何将值从子功能组件传递给父类组件? - How to pass value from a child functional component to parent class component? 如何将 React 表单状态从应用程序传递到多个组件(功能性) - How to Pass React form state from app to multiple components (functional) 使用 React Hooks 将 props 从父母传递给孩子 function - Using React Hooks to pass props down from a parent to a child function 如何从 React 中的子组件更新父组件(功能) - How to update Parent component from Child component in React (Functional)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM