如何解决如何在React中打印组件?
我正在制作一个简单的简历生成应用。
Index.js:
import ReactDOM from "react-dom";
import Resume from "../components/resume";
import React,{ useRef } from "react";
import { useReactToPrint } from "react-to-print";
const App = () => {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current
});
return (
<div className="bg-gray-200 p-6">
<button
type="button"
className="bg-gray-500 border border-gray-500 p-2 mb-4"
onClick={handlePrint}
>
{" "}
Print Resume{" "}
</button>
<Resume ref={componentRef} />
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />,rootElement);
简历是从components/resume.js
文件生成的,它是功能组件。.
我正在使用react-to-print库单独打印简历组件。
也引用了here的引用。.
但是在我的应用程序中,如果单击Print Resume
,则不会打印简历。
相反,我收到以下警告,
警告:不能为功能组件提供引用。尝试访问 该裁判将失败。您是要使用React.forwardRef()吗?
和另一个警告,
为使“反应印刷”仅起作用,可以使用基于类的组件
完整的工作示例:
https://codesandbox.io/s/tailwind-react-sandbox-forked-uivc8
请尝试单击以上链接中的Print Resume
按钮,其中该按钮不会打印简历。
您能帮我打印生成的简历吗?预先感谢。.
解决方法
您只需要使用React.forwardRef()
const Resume = React.forwardRef((props,ref) => {
// ...
return (
<div className="bg-gray-200 p-6" ref={ref}>
...
</div>
)
})
分叉的代码和框
,要打印的组件仍将是类组件,因此我将export default function ListItems() {
const defaultUser = {
id: null,photo: '',position: 0,name: '',email: '',phone: '',}
const [users,setUsers] = useState(defaultUser)
useEffect(() => {
displayUsers()
},[])
const displayUsers = () => {
API
.getUsers()
.then(response => {
setUsers(response.data)
console.log(response.data)
})
.catch(event => console.log(event))
}
return (
<ul className="list">
{
users && users.map(user => {
return (
<li className="item" key={ user.id }>
<img className="item__photo" src={ user.photo } alt="user-1"/>
<div className="item__name">
<h3 className="subtitle">{user.name}</h3>
</div>
<div className="item__description">
<h3 className="description">{user.position}</h3>
<h3 className="description">{user.email}</h3>
<h3 className="description">{user.phone}</h3>
</div>
</li>
)
})
}
</ul>
)
}
组件转换为类组件。
如果您尝试使用此方法作为推入Resume
的参考,即使简单的h1标记不是基于类的组件也可以使用。
在您经过编辑的sandbox上尝试一下。
如果您需要可靠的功能组件,则可以将<h1 ref={componentRef}>HELLO?</h1>
组件作为Resume
的子组件来迁移。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。