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



下面是条形图的示例。我想在浏览器中打印这个条形图,为此我尝试了反打印,但它抛出了一个错误,比如反打印只适用于类组件。

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

相关内容

  • 没有找到相关文章

最新更新