ReactforwardRef - 访问组件内和父级中的引用
我需要访问组件内文本区域的引用。在组件内,这很简单:
const MyComponent = () => {
const inputRef = useRef();
return <textarea ref={inputRef} />
}
现在 ref 在 MyComponent 中可用,我可以将它用于一些内部逻辑。
在某些情况下,我也需要从父组件访问引用。在这种情况下,我可以使用forwardRef:
const MyComponent = React.forwardRef((props, ref) => {
return <textarea ref={ref} />
})
// In some parent
const MyParent = () => {
const inputRefFromParent = useRef();
return <MyComponent ref={inputRefFromParent} />
}
现在我可以从父组件访问 textarea
的 ref,并将其用于父组件内的逻辑。
我发现自己处于这样的情况:我需要使用 MyComponent
中的引用执行一些内部逻辑,但我可能还需要从 MyParent
获取该引用。我该怎么做?
I need to access the ref to a textarea inside a component. Within the component, its easy enough:
const MyComponent = () => {
const inputRef = useRef();
return <textarea ref={inputRef} />
}
Now the ref is available within MyComponent and I can use it for some internal logic.
There are cases where I need to access the ref from the parent component as well. In that case, I can use forwardRef:
const MyComponent = React.forwardRef((props, ref) => {
return <textarea ref={ref} />
})
// In some parent
const MyParent = () => {
const inputRefFromParent = useRef();
return <MyComponent ref={inputRefFromParent} />
}
Now I can access to ref of the textarea
from the parent component, and use it for logic within the parent component.
I find myself in a situation where I need to do some internal logic with the ref within MyComponent
, but I may also need to get that ref from MyParent
. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在
MyComponent
中保留ref
并使用 useImperativeHandle 挂钩,使用从MyParent
传递的ref
。尝试如下所示。它将文本区域中的焦点方法公开给父级。您还可以通过访问
textAreaRef
执行任何其他内部操作。You can keep a
ref
in theMyComponent
and expose what you would need in the parent component using useImperativeHandle hook using theref
passed from theMyParent
.Try like below. It exposes the focus method in the textarea to parent. And you can do any other internal things with the access to
textAreaRef
.除了阿米拉的回答之外,我还找到了另一种方法,即使用 ref 回调:
因此回调 ref 对
textarea
的 ref 保持更细粒度的控制,并简单地将其值分配给本地引用和父引用。In addition to Amila's answer, I found another way to do it, by using a ref callback:
So the callback ref keeps finer grain control of the ref to the
textarea
, and simply assigns its value to both the local ref and the parent ref.对我有用的是:
What's working for me is:
要在转发引用的同时访问引用:
useImperativeHandle
挂钩(正在转发to)并传递一个返回内部引用的current
属性的函数,该值将被设置为外部引用的current
属性。这将整个参考暴露给消费者,而不是选择性地挑选某些属性。或者使用 TypeScript:
To access a ref while also forwarding it:
useImperativeHandle
hook on the outer ref (which is being forwarded to) and pass a function that returns thecurrent
property of the inner ref, which is the value that will be set to thecurrent
property of the outer ref. This exposes the entire ref to consumers rather than selectively picking certain properties.Or with TypeScript:
您还可以执行以下操作:
You could do also the following: