简体   繁体   English

尝试访问脚本时使用 useEffect 在我的 React 项目中获取“TypeError:无法读取 null 的属性 'classList'”?

[英]Getting “TypeError: Cannot read property 'classList' of null” on my React project with useEffect when trying to access a script?

I am trying to implement useEffect on my React project to add my external JS file in.我正在尝试在我的 React 项目上实现 useEffect 以添加我的外部 JS 文件。

This is my React code currently, with the commented out list being what I am trying to access from my script.这是我目前的 React 代码,注释掉的列表是我试图从我的脚本中访问的内容。

import React, { useEffect } from 'react';
import { Link } from 'react-router-dom';
import './HeroSec.css';
import '../script.js';

function HeroSec(){

    useEffect(() => {
        console.log('render');

        const script = document.createElement('script');

        script.src = "../script.js";
        script.async = true;
      
        document.body.appendChild(script);
      
        return () => {
          document.body.removeChild(script);
        }
    })

    return(
    <div className='hero-container'>

        <h1>Example Name </h1> 
        {/*
        <ul id="foo" class="hidden-text">
        <li> E </li>
        <li class="hidden">x</li>
        <li class="hidden">a</li>
        <li class="hidden">m</li>
        <li class="hidden">p</li>
        <li class="hidden">l</li>
        <li class="hidden">e</li>
        <li class="spaced">N</li>
        <li class="hidden">a</li>
        <li class="hidden">m</li>
        <li class="hidden">e</li>
        </ul>
        */}

and this is the script.js file I am getting the error in.这是我收到错误的 script.js 文件。

const text = document.querySelector("#foo");
    setTimeout(() => {
        text.classList.toggle("hidden-text");
    }, 1000);

Essentially, I am just trying to grab that list element in React, and use the script to set a timeout so I can toggle off the hidden-text class.本质上,我只是想在 React 中获取该列表元素,并使用脚本设置超时,以便我可以关闭隐藏文本 class。 Of course there is some CSS that does this separately.当然有一些 CSS 单独执行此操作。

Hopefully I made it easy to understand the bigger picture of what I am trying to do and any help on that would be appreciated.希望我可以很容易地理解我正在尝试做的事情的大局,并且对此的任何帮助将不胜感激。 In terms of the specific TypeError I am getting, is there maybe another property instead of classList that I can use to access the list from within React?就我得到的特定 TypeError 而言,是否有另一个属性而不是 classList 可以用来从 React 中访问列表?

This is not the "react" way of doing things, you should not be getting direct references to html elements and modifying them in React.这不是“反应”的做事方式,您不应该直接引用 html 元素并在 React 中修改它们。 I did not quite understand what you want to do but you can try below approach to render components differently according to the state.我不太明白你想做什么,但你可以尝试下面的方法来根据 state 以不同的方式渲染组件。

function HeroSec(){
  const [toggled,setToggled] = useState(false);
  ...

 return ( ....
 //Component will have different class based on the value of toggled and
 // when toggled value changed react will re-render the element with new value
 <ul id="foo" class={toggled ? : "hidden-text" : <another_classname>} >
  ...)

Then use setToggled in your setTimeout function to change toggled from false to true.然后在 setTimeout function 中使用 setToggled 将 toggled 从 false 更改为 true。

Ideally you use use the useRef hook to access element with React function components.理想情况下,您使用useRef挂钩来访问带有 React function 组件的元素。 For example:例如:

  export default function HeroSec() {
  const listElement = useRef(null);

  useEffect(() => {
    setTimeout(() => {
      listElement.current.classList.add("hidden-text");
    }, 1000);
    return () => {};
  });

  return (
    <div className="hero-container">
      <h1>Example Name </h1>
      <ul ref={listElement} id="foo">
        <li> E </li>
        <li className="hidden">x</li>
        <li className="hidden">a</li>
      </ul>
    </div>
  );
}

Sandbox: https://codesandbox.io/s/frosty-cache-6rkdq?file=/src/App.js沙盒: https://codesandbox.io/s/frosty-cache-6rkdq?file=/src/App.js

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

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