类型错误: 无法设置属性 'src' 的空值



我正在尝试使用react文件查看器预览.docx文件

<FileViewer
fileType={'docx'}
filePath={this.state.file} //this.state.file has path of the url data
id="output-frame-id"
allowFullScreen={true}
/>

当用户点击.docx文件进行预览时,它会抛出一个异常:

TypeError:无法设置空的属性"src">

并指向下方的代码

let srcData = URL.createObjectURL(this.response); // It contains a Response type of blob
error at this line ---> document.querySelector('#output-frame-id').src = srcData;

有什么建议吗?

https://github.com/plangrid/react-file-viewer

源代码

FileViewer.propTypes = {
fileType: PropTypes.string.isRequired,
filePath: PropTypes.string.isRequired,
onError: PropTypes.func,
errorComponent: PropTypes.element,
unsupportedComponent: PropTypes.element,
};

FileViewer.defaultProps = {
onError: () => null,
errorComponent: null,
unsupportedComponent: null,
};

我在文档中看不到id字段,也许这就是选择器返回null的原因。

应仅使用此字段:fileTypefilePathonErrorerrorComponentunsupportedComponent

如果您出于某种原因想要使用元素进行DOM操作,为此您可以使用div:包装您的元素

<div id="output-frame-id"
<FileViewer
fileType={'docx'}
filePath={this.state.file} //this.state.file has path of the url data
allowFullScreen={true}
/>
</div>

但我建议使用参考

我认为这是因为

document.querySelector('#output-frame-id') // equal to null

您能在开发者工具中检查一下React是否真的渲染了具有这样id的元素-输出帧id?我知道你的组件中有这个id,但React没有必要渲染它…这取决于FileViewer的实现,这个组件可能不支持id属性,因为这是一个自定义组件。

我不确定,但是,你可以尝试使用:

  1. 使用参考
  2. 在id之前使用冒号
:id="output-frame-id"

最新更新