[英]Getting a reference to a React Component using useRef hook
The current value in the reference object that useRef returns is always null. useRef返回的引用对象中的当前值始终为null。
I've reproduced the issue here https://codesandbox.io/s/runtime-field-hmusg 我在这里转载了这个问题https://codesandbox.io/s/runtime-field-hmusg
I want to get a reference to the component <MyComponent/>
我想获得对组件
<MyComponent/>
的引用
You actually need to use the forwardRef
method when dealing with functional components. 在处理功能组件时,实际上需要使用
forwardRef
方法。 Additionally, there is not a particular clean and easy way to retrieve the state-value of a functional-child component. 此外,还没有一种特别简单的方法来检索功能子组件的状态值。 But here is what you can do:
但是您可以执行以下操作:
import React, { useRef, useState, useImperativeHandle } from "react";
import ReactDOM from "react-dom";
function App() {
const referenceToMyComponent = useRef(null);
return (
<div className="App">
<button
onClick={() => {
if (referenceToMyComponent.current) {
console.log(referenceToMyComponent.current.returnStateValue());
}
}}
>
Print State reference
</button>
<MyComponent ref={referenceToMyComponent} />
</div>
);
}
const MyComponent = React.forwardRef((props, ref) => {
const [count, setCount] = useState(0);
const returnStateValue = () => {
return count;
};
useImperativeHandle(ref, () => {
return {
returnStateValue: returnStateValue
};
});
return (
<div>
<h4>Counter: {count}</h4>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
});
Essentially the key-points are the forwardRef
, useImperativeHandle
, and returnStateValue
. 本质上,关键点是
forwardRef
, useImperativeHandle
和returnStateValue
。
The forwardRef
helps us pass a ref coming from a parent to the functional child-component. forwardRef
帮助我们将来自父级的引用传递给功能forwardRef
组件。
The useImperativeHandle
hook helps us bind the ref
to the instance of the component, we still cannot extract the state-value from the child, but we can access functions defined in the child that would return the state-value anyway. useImperativeHandle
挂钩帮助我们将ref
绑定到组件的实例,我们仍然不能从子级中提取状态值,但是我们可以访问在子级中定义的函数,无论如何它们都将返回状态值。
The returnStateValue
function simply returns the state from inside the child-component. returnStateValue
函数只是从子组件内部返回状态。 We can now access that function via our ref by using referenceToMyComponent.current.returnStateValue()
现在,我们可以使用
referenceToMyComponent.current.returnStateValue()
通过referenceToMyComponent.current.returnStateValue()
访问该函数。
See working sandbox: https://codesandbox.io/s/dreamy-wiles-xst65 查看有效的沙箱: https : //codesandbox.io/s/dreamy-wiles-xst65
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.