在 React 中使用 getElementByID

IT技术 reactjs dom jsx
2021-05-06 17:12:30

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

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;

2个回答

通过在页面上定义,您似乎只有这个<Password />与“密码”相关的组件由于您正在使用getElementById(),您将需要能够定义元素的 id<Password id="password" />并将 props 传递到组件中,然后组件将分配 id 。

另外 ps 你有 HardDrvie 而不是 HardDrive

一些可以帮助你的事情:

  1. 首选使用refs来访问 React 中的 DOM 元素。
  2. 当渲染一个组件时,React 在它的虚拟 DOM 中创建你的应用程序的表示,然后将它与实际 DOM 进行比较,以便最大限度地减少代价高昂的 DOM 更新。这意味着在您尝试使用“getElementById()”时,该元素尚未添加到 DOM。
  3. 您正在使用一个函数组件,这将导致每次重新渲染组件时运行内联逻辑。为了避免重新运行这个应该只运行一次的逻辑,它应该被包装在 auseEffect或更少的频率中useLayoutEffect有关更多信息,请参阅文档)。

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

// 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} /> }
        </>
    )
}