document.getElementById() 为空反应

document.getElementById() is null react

我试图在我的代码中使用 document.getElementById('canvas') 获取 canvas 元素,但它不起作用。 请帮忙!我花了这个星期寻找解决方案,但我什么也没找到。

import React, { useEffect } from 'react'
import * as tf from '@tensorflow/tfjs'

const Analysis =  () => {

const canvas = document.getElementById('canvas')
console.log(canvas)
const ctx = canvas.getContext('2d').data
const img = new Image();
img.src = "Images/bg.jpg"
img.onload = function () {
        ctx.drawImage(img,0,0,256,256)
        data = context.getImageData(0,0,256,256)
        var input = [];
        for (var i = 0; i < data.length; i += 4) {
            input.push(data[i + 2] / 255);
        }
        predict(ctx)    
}
    var predict =  async function (input) {
        
    await tf.loadLayersModel('model.json').then(function(model){
        
        window.model= model
    });
        if (window.model) {
            window.model.predict(Input)
                .then(function (scores) {
                    scores = scores[0];
                    console.log(scores
                        .indexOf(Math.max(...scores)));
                });
                console.log('processing...')
        } else {
      
            // The model takes a bit to load, 
            // if we are too fast, wait
            setTimeout(function () { predict(input) }, 50);
        }
    }
return ( 
        <canvas id='canvas' width='1000' ></canvas>
     );
}
 
export default Analysis;

这是因为您试图在页面加载之前获取元素,将其包装在 useEffect:

useEffect(() => {
const canvas = document.getElementById('canvas')
console.log(canvas)
  }, []);

还建议使用 useRef 而不是 document.getElementById