ReactJS中使用react-to-print时componentRef的TypeError问题
问题原因及修复方案
错误原因
你用const componentRef = useRef()声明了一个常量变量,但在div的ref回调里直接尝试给componentRef本身赋值(componentRef=el),违反了const变量不可重新赋值的规则,因此抛出invalid assignment to const 'componentRef'错误。
修复步骤
只需修改ref回调的赋值逻辑,把DOM元素赋值给ref对象的current属性,而非ref变量本身:
核心修改部分
// 保持ref声明不变 const componentRef = useRef() // 修改ModalBody内的div ref <ModalBody> <div ref={el => (componentRef.current = el)}> /** 你要打印的内容 **/ </div> </ModalBody>
完整修复后的代码
import React, { useRef, useState } from "react" import Barcode from "../barcode/Barcode" import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap' import PrintButton from '../buttons/PrintButton' import { useReactToPrint } from "react-to-print" const PrintModal = forwardRef((props) => { const [basicModal, setBasicModal] = useState(false) console.log("data", props) const componentRef = useRef() console.log("componentRef", componentRef) const handlePrint = useReactToPrint({ content: () => componentRef.current, onafterprint: () => console.log("PRINT BERHASIL") }) return ( <div className='demo-inline-spacing'> <div className='basic-modal'> <Button color='primary' onClick={() => setBasicModal(!basicModal)}> Print </Button> <Modal isOpen={basicModal} toggle={() => setBasicModal(!basicModal)}> <ModalHeader toggle={() => setBasicModal(!basicModal)}>Print</ModalHeader> <ModalBody> <div ref={el => (componentRef.current = el)}> /** The content that I want to Print **/ </div> </ModalBody> <ModalFooter> <Button color='primary' onClick={handlePrint}> Print </Button> </ModalFooter> </Modal> </div> </div> ) }) export default PrintModal
额外简化建议
可以直接将ref变量绑定到div上,无需回调函数,React会自动把DOM元素赋值给componentRef.current:
<div ref={componentRef}> /** 你要打印的内容 **/ </div>
内容的提问来源于stack exchange,提问作者Gagak
相关产品推荐
相关产品推荐

