2

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

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>
  );
};
4

1 回答 1

0

在处理我的一个项目时,我尝试了很多方法来克服这个问题。终于想出了解决方案,也许它可以帮助某人。

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

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

随时感谢我:)

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>
    );
};
于 2021-05-19T14:18:14.160 回答