开发者问题收集

React 中的“scrollIntoView 无法读取‘null’的属性”错误

2022-11-22
1951

当我尝试单击导航栏上的某个项目时,我收到错误 Uncaught TypeError: Cannot read properties of null (reading 'scrollIntoView')

这是一个有点棘手的问题,但如果我从头开始加载页面,它会抛出上述错误。但是,如果我再次在 VSCode 中保存项目,它将正常工作,直到我刷新页面。有没有办法纠正这个问题?

Navbar.jsx:

import { useState } from 'react';
import { Link } from 'react-router-dom';
import '../App.css';
import myAvatar from '../images/avataaars.png';

function Navbar() {
    const aboutPage = document.getElementById('about');
    const home = document.getElementById('home');
    const skills = document.getElementById('skills');
    const [navbar, setNavbar] = useState(true);

    const handleNavbarToggle = (e) =>{
        setNavbar(!navbar);
    }

    return(
        <>
        <div className='navbar-container'>
            <Link to='/'><img src={myAvatar} className='nav-logo'/></Link>
            <ul>
                <li onClick={() =>{home.scrollIntoView({behavior: 'smooth'})}}>Home</li>
                <li onClick={() =>{aboutPage.scrollIntoView({behavior: 'smooth'})}}>About</li>
                <li onClick={() => {skills.scrollIntoView({behavior: 'smooth'})}}>Skills</li>
                <li>Projects</li>
                <li id='navbar-login-btn'>Login</li>
            </ul>
            <div className={`navbar-toggle ${navbar ? '' : 'open'}`} onClick={handleNavbarToggle}>
                <span></span>
                <span></span>
                <span></span>
            </div>
        </div>
        <div className={`navbar-header ${navbar ? 'navbar-header-hide' : ''}`}>
            <ul>
                <Link className='navbar-header-item' to='/'>Home</Link>
                <Link className='navbar-header-item' to='/about'>About</Link>
                <Link className='navbar-header-item' to='/skills'>Skills</Link>
                <Link className='navbar-header-item' to='/projects'>Projects</Link>
                <Link className='navbar-header-item' to='/login'>Login</Link>
            </ul>
        </div>
        </>
    )
}


export default Navbar;

App.js:

import { useState, useEffect } from 'react';
import { Route, Routes } from 'react-router-dom';
import TextTransition, { presets } from 'react-text-transition';
import './App.css';
import Navbar from './components/Navbar';
import Homepage from './components/Homepage';
import About from './components/About';
import Skills from './components/Skills';
import myAvatar from './images/avataaars.png';

function App() {

  return (
    <>
    <Navbar />
      <div className='homepage-container-web'>
        <Homepage />
        <About />
        <Skills />
      </div>
    <div className='homepage-container-devices'>
      <Routes>
        <Route path='/' element={<Homepage />} />
        <Route path='/about' element={<About />}/>
      </Routes>
    </div>
    </>
  );
}

export default App;

About.jsx:

import '../App.css';

function About() {
    return(
        <>
        <div className='about-container' id='about'>
            <h2 class='about-title'>A little bit about me...</h2>
            <p>Hi, my name is Andrew! I'm 20 years old, and I have <a href='https://www.crohnscolitisfoundation.org/what-is-crohns-disease' target="_blank" style={{color: '#a61bee'}}>Crohn's Disease</a>. Ever since I was 12 years old I have had an interest in technology, software engineering, cybersecurity, firefighting, and cars. I currently work for the Department of Defense and hold a Senior IT Specialist position. I am always looking to learn and improve myself.</p>
        </div>
        <div className='about-ending-container' />
        </>
    )
}

export default About;
1个回答

问题是,第一次渲染时,当您执行此操作时

const aboutPage = document.getElementById('about');
const home = document.getElementById('home');
const skills = document.getElementById('skills');

这些元素尚不存在。最简单的解决方案是将其更改为

const aboutPage = () => document.getElementById('about');
const home = () => document.getElementById('home');
const skills = () => document.getElementById('skills');

// ...

<li onClick={() =>{home().scrollIntoView({behavior: 'smooth'})}}>Home</li>
<li onClick={() =>{aboutPage().scrollIntoView({behavior: 'smooth'})}}>About</li>
<li onClick={() => {skills().scrollIntoView({behavior: 'smooth'})}}>Skills</li>

,以便在点击时进行搜索。这不是一种非常“反应”的方式。但它应该“正常工作”。

如果您想以“正确的方式”执行此操作,我想您会想要使用 useRef ,并将其提升到应用程序。仅使用 home 作为示例,并省略不相关的代码,它将类似于:

function App() {
    const homeRef = useRef();
    // ...
    <Navbar homeRef={homeRef} />
    // ...
    <Homepage ref={homeRef} />
}

function Navbar({ homeRef }) {
    const scrollIntoView = (ref) => {
        if (ref.current) {
            ref.current.scrollIntoView({behavior: 'smooth'})
        }
    }
    
    <li onClick={() =>{scrollIntoView(homeRef)}}>Home</li>
} 

const Homepage = React.forwardRef((props, ref) => {
    return(
        <>
            <div className='home-container' id='hone' ref={ref} >
                //...
            </div>
        </>
    )
})
dave
2022-11-22