如何在 React 中做 vanilla js 等效的 appendChild?

How to do vanilla js equivalent appendChild in React?

我已经用 vanilla js 编写了 this 笔。现在我想在我的 React 组件中使用它。

renderPDF(url, canvasContainer, options) {
  options = options || {
    scale: 1
  };

  function renderPage(page) {
    var viewport = page.getViewport(options.scale);
    var wrapper = document.createElement("div");
    wrapper.className = "canvas-wrapper";
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    var renderContext = {
      canvasContext: ctx,
      viewport: viewport
    };
    canvas.height = viewport.height;
    canvas.width = viewport.width;
    wrapper.appendChild(canvas);
    canvasContainer.appendChild(wrapper);

    page.render(renderContext);
  }

  function renderPages(pdfDoc) {
    for (var num = 1; num <= pdfDoc.numPages; num++)
      pdfDoc.getPage(num).then(renderPage);
  }
  PDFJS.disableWorker = true;
  PDFJS.getDocument(url).then(renderPages);
}

当我在 React 的 componentDidMount 生命周期内使用上述渲染函数时,出现 Cannot read property 'appendChild' of null

错误

请指导我用react方式编写上述功能?

这是我现在的 code-sandbox

由于 this.state = {visible: false};,您的 Modal 组件不会在第一次呈现,所以 .modal-container 在第一次呈现时不存在。它只会在您点击 'Open' 按钮后呈现。

为避免这种情况,您可以将 pdf 创建逻辑移动到单独的组件中并在 <Modal> 中呈现该组件。这是一个 example