因此,尝试将其运行几天已经开始,并且只是不考虑解决方案。这是我的第一个ReactJS项目,因为我更熟悉C#。
基本上,我正在尝试创建一个打印标签组件,当在调用该组件的菜单上单击链接时,该组件将触发打印对话框并打印此printLabel组件。我可以通过将组件加载到抽屉中并将触发器映射到按钮上的on-click事件上来使其工作,但是我不希望用户不必再单击一次。
import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';
class ComponentToPrint extends React.Component {
render() {
return (
<Col>
<Row>Customer Name</Row>
<Row>Address</Row>
<Row>City, State, Zip</Row>
</Col>
);
}
}
const PrintLabel = () => {
const componentRef = useRef();
return (
<div>
<ReactToPrint
trigger={() => <button>Print</button>}
content={() => componentRef.current}
/>
<ComponentToPrint ref={componentRef} />
</div>
);
};
导出默认的PrintLabel;
似乎响应打印不直接支持此行为。一种解决方案是在组件渲染时单击按钮(按ID查找)。这可以使用useEffect
挂钩(https://reactjs.org/docs/hooks-effect.html)完成。
import React, { useRef, useEffect } from 'react';
...
const PrintLabel = () => {
const componentRef = useRef();
useEffect(() => {
document.getElementById('print-button').click();
});
return (
<div>
<ReactToPrint
trigger={() => <button id="print-button">Print</button>}
content={() => componentRef.current}
/>
<ComponentToPrint ref={componentRef} />
</div>
);
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句