reactjs - 无法使用 React Hooks 从父函数访问子函数
问题描述
我需要使用 React Hooks 从父组件调用子组件中的函数。
我试图让这个问题适应我的用例React 16: Call children's function from parent when using hooks and functional component 但我一直收到错误
TypeError: childRef.childFunction is not a function
我的父组件是这样的:
import React, { useRef, useEffect } from 'react';
import Child from './child'
function Parent() {
const parentRef = useRef()
const childRef = useRef()
const callChildFunction = () => {
childRef.current(childRef.childFunction())
}
useEffect(() => {
if (parentRef && childRef) {
callChildFunction();
}
}, [parentRef, childRef])
return (
<div ref={parentRef} className="parentContainer">
PARENT
<Child ref={childRef}/>
</div>
);
}
export default Parent;
我的子组件是这样的:
import React, { forwardRef, useImperativeHandle } from 'react';
const Child = forwardRef(({ref}) => {
useImperativeHandle(ref, () => ({
childFunction() {
console.log("CHILD FUNCTION")
}
}));
return (
<div className="childContainer">
CHILD
</div>
);
})
export default Child;
我究竟做错了什么?
解决方案
我认为这是你的问题
childRef.current(childRef.childFunction())
childRef.current
不是函数。也childRef.childFunction()
首先运行,这也不是一个函数。
childRef.current.childFunction
应该是一个函数,尝试childRef.current.childFunction()
而不是childRef.current(childRef.childFunction())
从文档中useImperativeHandle
查看以下内容的用法inputRef.current.focus()
:
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
在此示例中,渲染的父组件<FancyInput ref={inputRef} />
将能够调用inputRef.current.focus()
.
根据未来访问者的评论进行编辑:
const Child = forwardRef(({ref}) => {
应该
const child = forwardRef(({}, ref) => {
推荐阅读
- path - 如何列出文件夹并返回特定文件类型的所有文件名?
- c# - 使用 ASP.NET MVC 和 IIS 10 浏览网站时出现错误 404
- json - JSON API - DirectException("请求正文不是 unjson()-able: %s" % body)
- google-cloud-platform - 从谷歌云存储库克隆项目作为成员
- c# - Sql server 过程选择作为插入过程的警报
- xml - 如何使用 one2many 字段为 many2one 字段设置域
- angular - 有没有办法在 Angular PipeDate 上实现 i18n
- java - 为此程序强制转换 IllegalArgumentException
- javascript - 为 json 对象的属性名称创建模型
- automationanywhere - 是否有用于打开目录文件的系统变量?