首页 > 解决方案 > 类组件中的 UseRef。画布未定义

问题描述

我正在尝试将我的功能组件代码转换为类组件代码,同时我在转换类组件中的 UseRef 时遇到了一些困难我尝试使用 this.refs.canvas 但它说它已贬值我需要隐藏此代码请指导我在这里将我的代码上传到功能组件和我尝试的类组件中。它没有显示错误,但仍然无法获得所需的输出矩形没有出现在图像上。

功能组件:

import React, { useRef, useEffect, useState } from "react";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";

function App() {
  const [data, setData] = useState([]);
  const canvas = useRef();
  let ctx = null;

  // initialize the canvas context
  useEffect(() => {
    // dynamically assign the width and height to canvas
    const canvasEle = canvas.current;
    canvasEle.width = canvasEle.clientWidth;
    canvasEle.height = canvasEle.clientHeight;

    // get context of the canvas
    ctx = canvasEle.getContext("2d");
  }, []);

  const drawRect = (info, style = {}) => {
    const { x, y, w, h } = info;
    const { borderColor = "black", borderWidth = 1 } = style;

    ctx.beginPath();
    ctx.strokeStyle = borderColor;
    ctx.lineWidth = borderWidth;
    ctx.rect(x, y, w, h);
    ctx.stroke();
  };

  const getData = () => {
    fetch("/test.json", {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    })
      .then(function (response) {
        console.log(response);
        return response.json();
      })
      .then(function (myJson) {
        console.log(myJson.annotations[0].bbox);
        setData(myJson.annotations[1].bbox);
        const x1 = myJson.annotations[2].bbox[0];
        const y1 = myJson.annotations[2].bbox[1];
        const w1 = myJson.annotations[2].bbox[2];
        const h1 = myJson.annotations[2].bbox[3];
        const r1Info = { x: x1, y: y1, w: w1, h: h1 };
        const r1Style = { borderColor: "red", borderWidth: 5 };
        drawRect(r1Info, r1Style);
      });
  };
  useEffect(() => {
    getData();
  }, []);
  // draw rectangle

  return (
    <div className="App">
      <canvas
        style={{
          height: "512px",
          width: "512px",
          backgroundImage: `url(${"https://karthiknbucket1.s3.ap-southeast-1.amazonaws.com/00000002.png"})`,
          backgroundPosition: "center",
          backgroundSize: "100% 100%",
        }}
        ref={canvas}
      ></canvas>
    </div>
  );
}

export default App;

我尝试的类组件:


    import React from 'react';
     import './App.css'
    import 'bootstrap/dist/css/bootstrap.min.css';
    class Apps extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
              
             
            }
            this.canvas = React.createRef();
          }
    
        // initialize the canvas context
        componentDidMount() {
          const canvas = this.canvas
          let ctx = null;
          // dynamically assign the width and height to canvas
          const canvasEle = canvas.current;
    
       
          // get context of the canvas
          ctx = canvasEle.getContext("2d");
         
         const getData=()=>{
          
            fetch('/test.json'
            ,{
              headers : { 
                'Content-Type': 'application/json',
                'Accept': 'application/json'
               }
            }
            )
              .then(function(response){
                console.log(response)
                return response.json();
              })
              .then(function(myJson) {
                console.log(myJson.annotations[0].bbox);
                const x1 = myJson.annotations[2].bbox[0];
                const y1 = myJson.annotations[2].bbox[1];
                const w1= myJson.annotations[2].bbox[2];  
                const h1 = myJson.annotations[2].bbox[3];
                const r1Info = { x:x1 , y:y1, w:w1, h:h1  };
                const r1Style = { borderColor: 'red', borderWidth: 5 };
                drawRect(r1Info, r1Style);
                 
              });
              const drawRect = () =>  (info, style = {}) => {
            const { x, y, w, h } = info;
            const { borderColor = 'black', borderWidth = 1 } = style;
         
            ctx.beginPath();
            ctx.strokeStyle = borderColor;
            ctx.lineWidth = borderWidth;
            ctx.rect(x, y, w, h);
            ctx.stroke();
          }
          
          }
          return  getData(); 
        }
    
      // draw rectangle
    
     render(){
    
      return (
        <div className="App">
          
          <canvas style={{height:"512px" ,width:"512px",backgroundImage:`url(${"https://karthiknbucket1.s3.ap-southeast-1.amazonaws.com/00000001.png"})`,
        backgroundPosition:"center",backgroundSize:"100% 100%"
        }}ref={this.canvas}></canvas>
    
        </div>
        
      );
    }
    }
     
    export default Apps;

它没有显示错误,但矩形框没有出现在图像上

标签: reactjscanvasuse-refreact-class-based-component

解决方案


我想说你需要使用 React 的 createRef 函数来初始化 ref。这类似于您在功能组件中的使用方式 const canvas = useRef();

例如:

constructor(props) {
    super(props);
    this.canvasRef = React.createRef();
}

推荐阅读