在React中使用getElementByID [英] using getElementByID in React

查看:595
本文介绍了在React中使用getElementByID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到无法读取null的属性'style'"在我的getElementById('password')上,但其在页面上已明确定义.我是新来的反应者,我猜这是不允许的.但是我试图显示密码页面,直到它的样式更改为无"为止,这发生在不同的组件中.

I am getting a "Cannot read property 'style' of null" on my getElementById('password'), but its clearly defined on the page. I'm new to react, and I'm guessing this isn't allowed or something. But I'm trying to have the password page show until, its style is changed to "none", which happens in a different component.

function App() {
  const [loggedIn, setLoggedIn] = useState(false)

  if (document.getElementById('password').style.display = "block"){
    setLoggedIn(false)
  } else {
    setLoggedIn(true)
  }

  return (
    <div className="app">
      { //Check if message failed
        (loggedIn)
          ? <div> <Password /> </div> 
          : <div> 
              <Nav />
              <div id="allFiles">
                <FileEarth title="Earth Update"/>
                <FileMars title="Mars Rover Update"/>
                <HardDrvie title="ASTRO Entertainment"/>
                <Folder title="Moon Pics"/>
              </div>
            </div> 
      } 
    </div>
  );
}

export default App;

推荐答案

一些可以帮助您的事情:

A few things that could help you out:

  1. 最好使用 refs 来访问DOM React中的元素.
  2. 在渲染组件时,React在虚拟DOM中创建您的应用程序的表示形式,然后将其与实际DOM进行比较,从而将昂贵的DOM更新减到最少.这意味着在您尝试使用'getElementById()`时,该元素尚未添加到DOM中.
  3. 您正在使用功能组件,这将导致每次重新渲染组件时都运行内联逻辑.为了避免重新运行仅应运行一次的逻辑,该逻辑应包装在useEffect或更少的情况下包装在useLayoutEffect中(请参阅文档以获取更多信息).
  1. It is preferred to use refs to get access to DOM elements in React.
  2. When rendering a component React creates a representation of your app in it's virtual DOM and then diffs this against the actual DOM so that it minimises DOM updates that are expensive. This means that at the point you are attempting to use 'getElementById()` the element has not yet been added to the DOM.
  3. You are using a function component which will result in your inline logic being run every time the component re-renders. To avoid rerunning this logic that should only run once it should be wrapped in a useEffect or less often a useLayoutEffect (see the docs for more information).

从我可以看到的回调函数应该可以做你想要的事情:

From what I can see a callback function should be able to do what you want:

// The password component gets passed the callback function as a prop.
// In this case the callback function would be onLogin.
// When clicking the div the callback function that was provided by
// the parent will be called and the state on the parent will be 
// updated.
const Password = ({ onLogin }) => {
    return (
        <div
            onClick={onLogin}
        >
            Login
        </div>
    );
}

// Parent component.
const Parent = () => {
    // Create state to store if the user is logged in or not.
    const [loggedIn, setLoggedIn] = React.useState(false);

    // Create callback function to pass to the Password component.
    // useCallback ensures that the function is only recreated when
    // a variable in the dependency array is updated.
    // The dependency array uses a reference compare to check for changes.
    const onLogin = React.useCallback(() => {
        setLoggedIn(true);
    }, [setLoggedIn] /* Dependency Array - recreate on setLoggedIn change */ );


    return (
        <>
            <div>
                {/* Write out loggedIn value for debugging. */}
                { loggedIn ? "Logged In" : "Not Logged In" }
            </div>
            {/* Conditionally render password component passing onLogin */}
            { !loggedIn && <Password onLogin={onLogin} /> }
        </>
    )
}

这篇关于在React中使用getElementByID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆