Is using document.getElementById in React an anti-pattern? [closed]

久未见 提交于 2020-03-06 09:22:13

问题


I am doing this at some point in my React app:

document.getElementById(element).scrollIntoView({ behavior: "smooth" });

As a beginner, I have two questions around this:

1) Is this considered bad practice in React? Should I rather use refs?

2) Am I technically modifying the DOM in any way using this technique? As far as I know, I am not, but maybe there's something going on in the background I'm not aware of.


回答1:


In general, refs is better than document.getElementById, because it is more in line with the rest of your react code.

In react, every component class can have multiple component instances. Also using id is dangerous, because react does not prevent you to have multiple forms on 1 page, and then your DOM contains multiple inputs with same ID. And that is not allowed.

Another advantage to using refs, is that by design, you can only access the refs in the context where you define it. This forces you to use props and state (and possibly stores) if you need to access info outside of this context. And this an advantage, because there is less/ no chance of you breaking your unidirectional data flow, which would make your code less manageable.

NB: In almost all cases, refs can be avoided altogether. It is a design principle for Netflix to use no refs, ever, as explained by Steve McGuire (Senior User Interface Engineer at Netflix) in this video from reactjs conf 2016 (9:58m into the video). In your case, this would mean putting the email-input value in state of the form, add on onChange handler, and use the state value in the submit event.



来源:https://stackoverflow.com/questions/60454476/is-using-document-getelementbyid-in-react-an-anti-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!