简体   繁体   English

html 元素无法反应

[英]Trouble getting html element in react

I am trying to add an script to an element created by a react component.我正在尝试将脚本添加到由反应组件创建的元素中。 The idea is to draw some effects in a canvas of id="matrix" using the script.这个想法是使用脚本在 id="matrix" 的 canvas 中绘制一些效果。

I have successfully added the script to my index.html and I am trying to execute it.我已成功将脚本添加到我的 index.html 中,我正在尝试执行它。 However, my document.getElementById("matrix") returns null .但是,我的document.getElementById("matrix")返回 null

List of things I tried to do:我尝试做的事情清单:

  1. useEffect of this answer .这个答案的使用效果。
  2. Change import script to end of body tag.将导入脚本更改为正文标记的结尾。
  3. Change document.getElementById("matrix") to document.querySelector("#matrix")document.getElementById("matrix")更改为document.querySelector("#matrix")

My index.html body :我的 index.html 主体

<body>
    <div id="root" class="has-navbar-fixed-top"></div>
    <script async scr="../src/MatrixEffect/matrix.js"></script>
</body>

matrix.js (script) : matrix.js(脚本)

window.onload = Init;

function Init() {
  const canvas = document.getElementById("matrix");
  /* const canvas = document.querySelector("#matrix"); */
  console.log(canvas); /*returns null */
  const context = canvas.getContext("2d");
}

MatrixComponent.js :矩阵组件.js


import styles from "./Matrix.module.css";

const MatrixComponent = () => {
  return (
    <div className={`${styles.container}`}>
      <canvas id="matrix" className={`${styles.canvas}`}></canvas>
    </div>
  );
};

export default MatrixComponent;

Error:错误:

matrix.js:7 Uncaught TypeError: Cannot read properties of null (reading 'getContext') at Init (matrix.js:7:1) matrix.js:7 Uncaught TypeError: Cannot read properties of null (reading 'getContext') at Init (matrix.js:7:1)

I got to make it work by using refs:我必须通过使用 refs 使它工作:

React functions:反应函数:

export default function MatrixComponent() {
  const ref = useRef();

  useEffect(() => {
    if (ref.current) {
      const canvas = ref.current;

      
      console.log(canvas);
      const context = canvas.getContext("2d");
      /* rest of code */
    }
  }, []);

  return (
    <div className={`${styles.container}`}>
      <canvas ref={ref} className={`${styles.canvas}`} />
    </div>
  );
}

React classes:反应类:

import React from "react";

class MatrixComponent2 extends React.Component {
  constructor(props) {
    super(props);

    this.matrix = React.createRef();
  }

  componentDidMount() {
    this.context = this.matrix.current.getContext("2d");
    /*rest of code*/
  }

  render() {
    return <canvas ref={this.matrix} />;
  }
}
export default MatrixComponent2;

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

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