簡體   English   中英

如何將文件從 electronjs 菜單渲染到反應元素?

[英]How do I render a file from the electronjs menu to a react element?

我正在嘗試將圖像路徑從主進程傳遞給我的 App.js。 截至目前,我遇到的問題是我的 canvas 元素是 null: TypeError: Cannot read property 'drawImage' of null 我不太清楚為什么。 這是我的App.js

import React from "react";
import { Router, Route, Link } from "react-router-dom";
import { Grid, Paper, makeStyles } from "@material-ui/core/";
import Tools from "./Tools.js";
import Dropzone from "./Dropzone.js";
import { createBrowserHistory as createHistory } from "history";
const history = createHistory();

class App extends React.Component {
  constructor(props) {
    super(props);
    this.myCanvas = React.createRef();
  }

  render() {
    const canvas = this.myCanvas.current;
    window.ipcRenderer.on("upload", (event, img) => {
      canvas.drawImage(img);
    });
    return (
      <Router history={history}>
        <Route path="/">
          <Tools />
          <canvas
            id="myCanvas"
            width="600"
            height="400"
            ref={this.myCanvas}
            style={{ border: "1px solid #000000" }}
          ></canvas>
        </Route>
      </Router>
    );

  }
}

export default App;

我嘗試使用document.getElementById('myCanvas')但經過研究,了解到這不是獲取元素的正確方法。 使用參考時,我仍然得到這個 null 值。 我認為這與尚未加載到 DOM 中的組件有關,但我不確定。

在組件第一次渲染之前設置upload事件監聽器。 此時, myCanvas尚未設置(即myCanvas.currentnull )。

在確保已設置myCanvas后,您應該簡單地創建upload事件偵聽器。

為此,您可以使用componentDidMount

class App extends React.Component {
  constructor(props) {
    super(props);
    this.myCanvas = React.createRef();
  }

  componentDidMount() {
    const canvas = this.myCanvas.current;
    window.ipcRenderer.on("upload", (event, img) => {
      canvas.drawImage(img);
    });
  }

  render() {
    return (
      <Router history={history}>
        <Route path="/">
          <Tools />
          <canvas
            id="myCanvas"
            width="600"
            height="400"
            ref={this.myCanvas}
            style={{ border: "1px solid #000000" }}
          ></canvas>
        </Route>
      </Router>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM