【问题标题】:How to pass down event from parent to child in react with functional components?如何将事件从父级传递给子级以与功能组件做出反应?
【发布时间】:2023-04-07 05:02:01
【问题描述】:

我的父组件中有两个按钮 AddRow 和 DeleteRow 按钮 如果我单击 addRow 按钮,它将在网格中添加一个空行,如果我单击 deleteRow 按钮,它将从网格中删除选定的行。 我在子组件中添加了两个函数,用于将行添加到网格并从网格中删除记录。 如何从父组件按钮点击事件中调用这些函数。 下面给出了类似的示例代码。

我已经使用提升状态到父组件它正在工作是任何其他方式来做到这一点,因为我需要将整个子组件代码移动到父组件并且有 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'));

点击父组件AddNewElement按钮需要调用addElement()函数。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你应该lift your state up。将functionsstate 移动到父级并通过props 将其传递下来。请记住,React 完全是关于 data flowing down 组件的树,永远不会向上。

    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'));
    

    【讨论】:

    • 这个。子调用父函数比父调用子函数更有意义。向下传递函数是微不足道的。
    【解决方案2】:

    如果我要说什么是反应方式来做到这一点,它会是这样的:

    父组件:

    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>
      );
    }
    

    子组件:

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

    使用 react 的要点之一是跳过动态渲染到应用程序中的某个任意点(如 id="uniqueIdHere"),无论您使用 jQuery 还是新的 JS 语法来定位它然后改变 JS 都无关紧要。如果 React 使用得当,它将确保只重新渲染变化的节点(影子 DOM),并适当地跟踪状态(在任何时间点应该有多少节点)。

    正如您所看到的渲染新节点或删除它们的逻辑,以一种专为使用而构建的方式使用 react 并没有那么大和可怕。

    这里有一个sandbox 可以玩,很高兴回答您对我编写的代码的任何问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 2017-06-24
      • 1970-01-01
      • 2020-10-21
      相关资源
      最近更新 更多