如何使用功能组件在浏览器中打印 react-chartjs-2 条形图?

How to print react-chartjs-2 bar chart in browser using functional component?

这是条形图的示例。我想在浏览器中打印此条形图,为此我尝试了 react-to-print 但它抛出错误,如 react-to-print 仅适用于 class 组件。

import React from "react";
import { Bar } from "react-chartjs-2";

// dataset for bar chart
const data = {
  // goes onto X-axis
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [
    {
      
      label: "My First dataset",
      fill: false,
      // background color 
      backgroundColor: "rgba(75,192,192,0.4)",
      // border color 
      borderColor: "rgba(75,192,192,1)",
      // goes onto y-axis
      data: [65, 59, 80, 81, 56, 55, 40]
    }
  ]
};


const options={
  //options for bar chart 
};

export const BarDemo = () => {
  return (
    <div>
      <h2>Bar Example</h2>
      <Bar data={data} />
    </div>
  );
};

在我的一个项目中,我尝试了很多方法来克服这个问题。 终于想出了解决办法,也许对某人有帮助。

首先,我使用功能组件创建了条形图,如您在上面给出的示例中所见。

所以,这里是所问问题的最终代码。

随时感谢我:)

import React,{useRef} from "react";
// import class component
import BarComponent from './BarComponent';

const data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [
    {
      label: "My First dataset",
      fill: false,
      backgroundColor: "rgba(75,192,192,0.4)",
      borderColor: "rgba(75,192,192,1)",
      data: [65, 59, 80, 81, 56, 55, 40]
    }
  ]
};

const options={
  //options for bar chart 
};

export const BarDemo = () => {

  const componentRef = useRef();

  return (
    <div>
      <h2>Bar Example</h2>
      //instead of using Bar directly,we will create a class component.
      <BarComponent ref={componentRef} data={data} options={options}/>
    </div>
  );
};


// here goes the class Component somethings like this.
import React from 'react';
import {Bar} from 'react-chartjs-2';

class BarComponent extends React.PureComponent {

  componentRef = React.createRef();

  render() {
    return (
        <div>
            <Bar ref={this.componentRef} id="Bar" data={this.props.data} options={this.props.options}/>
        </div>
    );
  }
};
export default BarComponent;


// we can pass the ref of BarComponent as props to the print functional component something like this

import React from 'react';
import { useReactToPrint } from "react-to-print";

export const Print = ({componentRef}) =>{
    
    // it will print the bar chart
    const handlePrint = useReactToPrint({
       content: () => componentRef.current
    });

    return(
      <button onClick={handlePrint}> Print </button>
    );
};