reactjs - 从 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/>
</>
);
}
解决方案
我创建了一个单例类并将我的函数订阅到一个侦听器函数,并在我的父组件中创建了该类的实例以从那里调用子组件的方法。
推荐阅读
- python - 绘制日期时间数据框会导致错误视图限制最小值 -36495.50013946759 小于 1
- c# - Visual Studio 跳转到黄色箭头(调试指针)
- python - 影响编码、解码和打印的 python 设置列表是什么?
- r - http请求发布带有标头的用户名和密码以在R中获取身份验证/密钥
- python - 在 ubuntu 18.04 上带有 Mod_WSGI 的 Django,带有 Apache2 媒体权限被拒绝/
- visual-studio-code - 用于 HTML、CSS 的包快速参考
- php - Telegram Bot 中的一次性键盘可能无法正常工作
- swift - 来自 youtube 的数据未使用委托传递
- android - 动态添加的 RadioButtons 不监听 onCheckChangedListener()
- java - 在插入行时动态增加 jtable 的高度