首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打印反应功能组件

打印反应功能组件
EN

Stack Overflow用户
提问于 2021-11-22 05:21:51
回答 2查看 1.6K关注 0票数 0

大家好,我已经开发了一个使用功能组件的react应用程序,我需要在应用程序中打印一个特定的页面。因为每个页面都是一个功能组件,我想也许我们可以单独打印一个组件。我试过使用,但它只支持类组件?这是通过一些NPM一揽子计划实现的吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-11-22 05:38:08

如常见问题中所述,您可以在功能组件中使用react-to-print

代码语言:javascript
复制
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>
  );
};
票数 2
EN

Stack Overflow用户

发布于 2022-10-18 03:18:04

是的,你可以只使用React forwardRef

为了在前面的答案的基础上,下面是两个有问题的文件:

Example.js

代码语言:javascript
复制
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

代码语言:javascript
复制
import { forwardRef } from 'react';

const ComponentToPrint = forwardRef(( props, ref ) => {
  return (
  <div ref={ref}>
    <p>{props.text}</p>
  </div>
)});

export default ComponentToPrint;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70061199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档