Uncaught Error: 'node' must be a RefObject when passing a React.RefObject

Uncaught Error: 'node' must be a RefObject when passing a React.RefObject

我正在尝试传递对 exportComponentAsPNG 函数的引用。

return (
    <div id="grid">
        <div id="pixels" ref={this.gridRef}>{rows}</div>

        {(() => {
            if (shouldExport) {
                exportComponentAsPNG(this.gridRef);
            } else {
                console.log("shouldn't export");
            }
        })()}

        <button onClick={() => exportComponentAsPNG(this.gridRef)} className="mocha-button">Export</button>
    </div>
)

this.gridRef 在构造函数中定义为:

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

exportComponentAsPNG(this.gridRef)button 组件配合使用。但是,当我尝试在 if 块中调用它时,出现以下错误:

Uncaught Error: 'node' must be a RefObject
    at d (index.js:171:1)
    at p (index.js:171:1)
    at Grid.js:38:1
    at Grid.render (Grid.js:42:1)
    at finishClassComponent (react-dom.development.js:20561:1)
    at updateClassComponent (react-dom.development.js:20507:1)
    at beginWork (react-dom.development.js:22440:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4161:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4210:1)
    at invokeGuardedCallback (react-dom.development.js:4274:1)

您能否解释一下为什么来自 if 块的调用不同以及如何解决它,因为在我的情况下使用按钮实现并不理想;我更愿意从 if 块中调用它。

girdRef.current 在第一个渲染中是 null。即使你让它与空检查一起工作,使用这样的函数也不是一个好习惯。

您应该根据需要使用componentDidMountcomponentDidUpdate来编写您的操作。

componentDidUpdate() {
  if (shouldExport) {
    exportComponentAsPNG(this.gridRef);
  } else {
    console.log("shouldn't export");
  }
}