[英]React forwardRef for function component
I have this interface:我有这个界面:
export interface INTERFACE1{
name?: string;
label?: string;
}
and then this function component:然后这个 function 组件:
export function FUNCTION1({
name,
label
}: INTERFACE1) {
return (
<CustomComponent name={name} label={label} />
);
}
my goal is to access this CustomComponent
from another component.我的目标是从另一个组件访问此
CustomComponent
。 I tried adding ref: React.createRef<any>
inside the interface but it didn't click in. From my research, it seems that I need to use forwardRef
but most of the online examples don't seem to work.我尝试在界面中添加
ref: React.createRef<any>
但它没有点击。根据我的研究,我似乎需要使用forwardRef
但大多数在线示例似乎都不起作用。 Any ideas how can I reference my CustomComponent
from outside, from different component, like this?任何想法如何从外部,从不同的组件引用我的
CustomComponent
,就像这样?
import React, { useCallback, useEffect, useState, createRef } from 'react';
import { FUNCTION1 } from 'FUNCTION1';
interface INTERFACE2 {
loading: boolean;
}
export default function FUNCTION2({
loading
}: INTERFACE2) {
const areaRef = createRef<HTMLTextAreaElement>();
return (
<>
<FUNCTION1
name="NAME"
label="LABEL"
ref={areaRef}
/>
</>
);
}
areaRef
throws an error that I should use forwardRef
. areaRef
抛出一个错误,我应该使用forwardRef
。
You don't really need a forwardRef
here, please refer to: Why, exactly, do we need React.forwardRef?你在这里真的不需要
forwardRef
,请参考: Why, exactly, do we need React.forwardRef? . .
In your specific example:在您的具体示例中:
useRef
in function components, createRef
is for classes.useRef
, createRef
用于类。function Foo2() {
const areaRef = useRef();
// Check ref
useEffect(() => {
console.log(areaRef.current);
}, []);
return <CustomComponent inneRef={areaRef} />;
}
function CustomComponent({ innerRef }) {
return <textArea ref={innerRef} />;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.