首页 > 解决方案 > 从 React 中的父功能组件调用子功能组件方法

问题描述

下面是我的子功能组件和父功能组件的代码。子组件使用一个库,它为我提供了重置功能,但我需要调用该重置功能的事件在父组件中。他们是一种从父组件调用子组件函数的方法吗?如果有人帮助我解决这个问题,我将不胜感激。

    

import React from 'react';
    export default function MyChildFunction() {
      const {
        Test
        reset,
      }
      return (
        <div style={{textAlign: 'center'}}>
          <div style={{fontSize: '30px', color : 'white'}}>
            <span>{Test}</span>:<span>{Test}</span>:<span>{Test}</span>
          </div>
        </div>    
      );
      function handleReset() {
          {reset()};
      }
    }

    export default function NavBar({
      return (
      <div>
                    <MyChildFunction/>
                    </div>
    )
    }

    import NavBar from "./components/NavBar";
            function App() {
            const changeUserState = (State) => {
                alert(State);
                MyChildFunction.handleReset(); -- here i want to have the function called.
                setState(State);
              };
        return (
            <>
         <NavBar/>
        </>
          );
            }

标签: reactjs

解决方案


我创建了一个单例类并将我的函数订阅到一个侦听器函数,并在我的父组件中创建了该类的实例以从那里调用子组件的方法。


推荐阅读