简体   繁体   English

如何在 React 中访问不在 JSX 中的 dom 元素?

[英]How to access dom element that is not inside JSX in React?

We are using ReactJS framework, so we don't find element written in the entire code.我们使用的是 ReactJS 框架,所以我们没有在整个代码中找到元素。 The only way is to find the DOM element and should set the attribute.唯一的方法是找到 DOM 元素并设置属性。 I am doing this in app.js.我在 app.js 中这样做。

setTimeout(function () {
  const formElement = document.getElementsByTagName('form')
  formElement.item(0).setAttribute('autocomplete', 'off')
}, 1000)

The above solution is working fine, but if the page loading is slow, then this will not set the attribute.上述解决方案工作正常,但如果页面加载缓慢,则不会设置属性。 Is there any other way to find the element and set the attribute?有没有其他方法可以找到元素并设置属性? I have also tried to set it using the below code after DOMContentLoaded, but it's not working.我也尝试在 DOMContentLoaded 之后使用以下代码设置它,但它不起作用。 Nothing inside this event is working.此事件中的任何内容都不起作用。

document.addEventListener('DOMContentLoaded', () => {
   const formElement = document.getElementsByTagName('form')
   formElement.item(0).setAttribute('autocomplete', 'off')
})

In React a good way to access DOM elements is by using useRef hook.在 React 中访问 DOM 元素的一个好方法是使用useRef钩子。 However, if that element you want to query is not in the JSX of your current component, the useEffect hook could be used with normal JavaScript DOM methods.但是,如果您要查询的元素不在当前组件的 JSX 中,则可以将useEffect挂钩与普通 JavaScript DOM 方法一起使用。 Like so:像这样:

useEffect(()=>{
  const formElement = document.getElementsByTagName('form')
  formElement.item(0).setAttribute('autocomplete', 'off')
},[]);

You don't find the element because 'DOMContentLoaded' gets fired when HTML file completes loading, not when React renders the form.您找不到该元素,因为“DOMContentLoaded”在 HTML 文件完成加载时触发,而不是在 React 呈现表单时触发。

How about using MutationObserver instead?改用 MutationObserver 怎么样? https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Also doing that in root level app.js sounds wrong.在根级别 app.js 中也这样做听起来是错误的。 Can you do it in the component that is closest to the container of the form?能不能在离表单容器最近的组件里做呢?

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

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