48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
|
|
import { useEffect, useRef } from "react";
|
||
|
|
import JsBarcode from "jsbarcode";
|
||
|
|
|
||
|
|
interface BarcodeDisplayProps {
|
||
|
|
value: string;
|
||
|
|
width?: number;
|
||
|
|
height?: number;
|
||
|
|
displayValue?: boolean;
|
||
|
|
className?: string;
|
||
|
|
}
|
||
|
|
|
||
|
|
export default function BarcodeDisplay({
|
||
|
|
value,
|
||
|
|
width = 2,
|
||
|
|
height = 50,
|
||
|
|
displayValue = true,
|
||
|
|
className = "",
|
||
|
|
}: BarcodeDisplayProps) {
|
||
|
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
if (canvasRef.current && value) {
|
||
|
|
try {
|
||
|
|
JsBarcode(canvasRef.current, value, {
|
||
|
|
format: "CODE128",
|
||
|
|
width,
|
||
|
|
height,
|
||
|
|
displayValue,
|
||
|
|
fontSize: 14,
|
||
|
|
margin: 10,
|
||
|
|
});
|
||
|
|
} catch (error) {
|
||
|
|
console.error("Error generating barcode:", error);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}, [value, width, height, displayValue]);
|
||
|
|
|
||
|
|
if (!value) {
|
||
|
|
return (
|
||
|
|
<div className={`flex items-center justify-center bg-gray-100 rounded border-2 border-dashed border-gray-300 p-4 ${className}`}>
|
||
|
|
<p className="text-gray-400 text-sm">尚未生成條碼</p>
|
||
|
|
</div>
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
return <canvas ref={canvasRef} className={className} />;
|
||
|
|
}
|