React Ref Ref处于状态,好还是坏实践?如何从另一个组件上获取某些DOM元素的参考
您好,我想问:在父母状态下存储裁判是“好”(好)还是不好的做法?
我需要的:
- 假设我们有父零件包装器。
- 内部包装器我有2个组件,componenta和componentB
- componenta具有一些重要元素,当它渲染时,我必须参考
- ComponentB,不幸的是,它必须从ComponentA的参考中呈现一些属性,但
不幸的是,ComponentA是无效的,并且在应用程序启动时不存在。该组件是根据其他内容动态初始化的。如果我创建Ref并将其通过包装组件中的道具将其传递,则不幸的是它仍然是无效的。在Componenta(初始化时),我可以成功地达到参考,不幸的是,包装器对其初始化不了解。
这就是为什么我要考虑而不是转发此裁判,而是考虑转发我想保留参考的状态。在Componenta中,接收参考并设置参考。这就是包装器将识别更改的裁判的方式,而我应该将REF转移到ComponentB,我将能够获得该属性。
还有什么(更好的解决方案)可以解决这个问题吗?
Hello I would like to ask, is it "good" (ok) or bad practise to store ref in parents state?
What I need:
- Lets assume we have parent component WRAPPER.
- Inside WRAPPER I have 2 components, ComponentA and ComponentB
- ComponentA has some important element which I have to reference
- ComponentB, when its rendered has to render some attributes from the reference from ComponentA
Unfortunately, ComponentA is null and does not exist when the application starts. This component is initialized dynamically based on something else. If I create the ref and pass it through props in WRAPPER component, unfortunately it remains null. In ComponentA (when it is initialized) I can successfully reach the reference, unfortunately WRAPPER does not know about its initialization.
That is why I am thinking about instead of forwarding this ref, I think about forwarding state in which I would like to keep the reference. In ComponentA receive the ref and set the Ref. This is how WRAPPER will recognize the ref changed and than I should pass the ref to ComponentB in which I will be able to get the attributes.
Is there anything else (better solution) to solve this one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要基于该裁判
store a ref into a state is totally alright if you need some re-render based on that one
tl; dr:使用上下文 Elements的LifeCycles:
在这里。
nl; pr:在反应中,状态引用(不打算)可以序列化的数据值。 REF和其他功能以及其他程序引用无法序列化。这样做,打破水合。
由于两者都可以用作道具,因此会引起混乱。
TL;DR: use contexts to separate state, hooks, and elements' lifecycles:
Check it out here.
NL;PR: In React, state refers (no pun intended) to data values that can be serialized. Refs and other functions and other program references cannot be serialized. Doing so, breaks hydration.
Since both can be used as props, it causes confusion.