[英]Can't access child function from parent function with React Hooks
I need to call a function in a child component from a parent component with React Hooks.我需要使用 React Hooks 从父组件的子组件中调用 function。
I was trying to adapt this question to my use case React 16: Call children's function from parent when using hooks and functional component but I keep getting the error我试图让这个问题适应我的用例React 16: Call children's function from parent when using hooks and functional component但我一直收到错误
TypeError: childRef.childFunction is not a function
My parent component is like this:我的父组件是这样的:
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;
My child component is like this:我的子组件是这样的:
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;
What am I doing wrong?我究竟做错了什么?
I think this is your problem我认为这是你的问题
childRef.current(childRef.childFunction())
childRef.current
isn't a function. childRef.current
不是 function。 Also childRef.childFunction()
is run first, which also isn't a function.还首先运行childRef.childFunction()
,这也不是 function。
childRef.current.childFunction
should be a function, try childRef.current.childFunction()
instead of childRef.current(childRef.childFunction())
childRef.current.childFunction
应该是 function,尝试childRef.current.childFunction()
而不是childRef.current(childRef.childFunction())
From the docs on useImperativeHandle
check out the usage of inputRef.current.focus()
:从useImperativeHandle
的文档中查看inputRef.current.focus()
的用法:
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
In this example, a parent component that renders <FancyInput ref={inputRef} />
would be able to call inputRef.current.focus()
.在此示例中,呈现<FancyInput ref={inputRef} />
的父组件将能够调用inputRef.current.focus()
。
Edit based on comment for future visitors:根据未来访问者的评论进行编辑:
const Child = forwardRef(({ref}) => {
should be应该
const child = forwardRef(({}, ref) => {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.