大家好,我已经开发了一个使用功能组件的react应用程序,我需要在应用程序中打印一个特定的页面。因为每个页面都是一个功能组件,我想也许我们可以单独打印一个组件。我试过使用,但它只支持类组件?这是通过一些NPM一揽子计划实现的吗?
发布于 2021-11-22 05:38:08
如常见问题中所述,您可以在功能组件中使用react-to-print。
import React, { useRef } from 'react';
import ReactToPrint from 'react-to-print';
import { ComponentToPrint } from './ComponentToPrint';
const Example = () => {
const componentRef = useRef();
return (
<div>
<ReactToPrint
trigger={() => <button>Print this out!</button>}
content={() => componentRef.current}
/>
<ComponentToPrint ref={componentRef} />
</div>
);
};发布于 2022-10-18 03:18:04
是的,你可以只使用React forwardRef。
为了在前面的答案的基础上,下面是两个有问题的文件:
Example.js
import React, { useRef, useState } from 'react';
import ReactToPrint from 'react-to-print';
import { ComponentToPrint } from './ComponentToPrint';
const Example = () => {
const componentRef = useRef();
const [text, setText] = useState('Hello world!');
return (
<div>
<ReactToPrint
trigger={() => <button>Print this out!</button>}
content={() => componentRef.current}
/>
<ComponentToPrint ref={componentRef} text={text} />
</div>
);
};您的打印:
ComponentToPrint.js
import { forwardRef } from 'react';
const ComponentToPrint = forwardRef(( props, ref ) => {
return (
<div ref={ref}>
<p>{props.text}</p>
</div>
)});
export default ComponentToPrint;https://stackoverflow.com/questions/70061199
复制相似问题