简体   繁体   English

如何在反应中将 document.getElementById() 与样式组件一起使用?

[英]How to use document.getElementById() with styled components in react?

I want to use JS functions like document.getElementById() in my react project.我想在我的反应项目中使用像document.getElementById()这样的 JS 函数。 I am new to styled components and don't know how to use these functions with them.我是样式组件的新手,不知道如何将这些功能与它们一起使用。 Do not refer to the official 'styled-components' page, I have already seen it.不要参考官方的“样式组件”页面,我已经看过了。

You can use useRef react Hook for this.您可以useRef使用useRef react Hook。

const reqElement = React.useRef(null);

Now, you can add ref={reqElement} in your required element.现在,您可以在所需元素中添加ref={reqElement}

After that you can use reqElement.current to do those things that you can do via document.getElementById() in javaScript.之后你可以使用reqElement.current来做那些你可以通过 javaScript 中的document.getElementById()做的事情。

useRef hook refrence useRef 钩子引用

I have finally found an answer to my question here.我终于在这里找到了我的问题的答案。 I laying down the gathered information in the following points.我将收集到的信息分为以下几点。

  1. Styled Components does have an id parameter but we must not use it in react for DOM functionalities as the main motive behind react is to prevent frequent changes in the real DOM. Styled Components 确实有一个 id 参数,但我们不能在反应 DOM 功能时使用它,因为反应背后的主要动机是防止真实 DOM 中的频繁更改。
  2. We can use useRef() hook in React functional components for passing references in react.我们可以在 React 功能组件中使用useRef()钩子在 React 中传递引用。 (Look at Dibas's answer above.) (看看上面迪巴斯的回答。)
  3. I was making a mistake of not using useState() hook to store the state of the component, instead I used an identifier, which is wrong as useState helps to re render the component whenever the state changes.我犯了一个错误,没有使用useState()钩子来存储组件的状态,而是使用了一个标识符,这是错误的,因为useState有助于在状态改变时重新渲染组件。
  4. Use a cleaning function in useEffect() hook to prevent memory leak.useEffect()钩子中使用清理函数来防止内存泄漏。

Here is a link to a Parallax effect video https://youtu.be/Q5y6pwoE3cM hope this can help you.这是一个视差效果视频的链接https://youtu.be/Q5y6pwoE3cM希望这可以帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM