React 生成條形碼代碼
注:需引入 jsbarcode
插件
import React from 'react'; import JsBarcode from 'jsbarcode'; class Widget extends React.Component { constructor(props) { super(props); this.state = { value: 1234567890, //由父組件傳入用來生成條形碼的字符串“barCode” }; } componentDidMount() { this.toJsBarcode(); } toJsBarcode(){ // 調用 JsBarcode方法生成條形碼 JsBarcode(this.barcode, "1234567890", { text: "顯示文案", format: "CODE39", displayValue: true, width: 2.0, height: 100, margin: 0, }); } render() { return ( <div className="barcode-box"> <svg ref={(ref) => { this.barcode = ref; }} /> </div> ); } } export default Widget;
HTML 生成條形碼代碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no" /> <title></title> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/JsBarcode.all.js"></script> </head> <body> <svg id="svgcode"></svg> <!-- or --> <canvas id="canvascode"></canvas> <!-- or --> <img id="imgcode" /> <script> $("#svgcode").JsBarcode('顯示文案'); $("#canvascode").JsBarcode('顯示文案'); $("#imgcode").JsBarcode("顯示文案"); </script> </body> </html>
生成條形碼如圖:
注意:引用 JsBarcode 最好是引用 JsBarcode.all.min.js 這個js包,它支持所有條形碼!
JsBarcode參數All Options:
Option | Default value | Type |
---|---|---|
format(選擇要使用的條形碼類型) | "auto" (CODE128) | String |
width(設置條之間的寬度) | 2 | Number |
height(高度) | 100 | Number |
displayValue(是否在條形碼下方顯示文字) | true | Boolean |
text (覆蓋顯示的文本) | undefined | String |
fontOptions(使文字加粗體或變斜體) | "" | String |
font(設置文本的字體) | "monospace" | String |
textAlign(設置文本的水平對齊方式) | "center" | String |
textPosition(設置文本的垂直位置) | "bottom" | String |
textMargin(設置條形碼和文本之間的間距) | 2 | Number |
fontSize(設置文本的大小) | 20 | Number |
background(設置條形碼的背景) | "#ffffff" | String (CSS color) |
lineColor(設置條和文本的顏色) | "#000000" | String (CSS color) |
margin(設置條形碼周圍的空白邊距) | 10 | Number |
marginTop(設置條形碼上方的空白邊距) | undefined | Number |
marginBottom(設置條形碼下方的空白邊距) | undefined | Number |
marginLeft(設置條形碼左邊的空白邊距 | undefined | Number |
marginRight(設置條形碼右邊的空白邊距) | undefined | Number |
flat | false | Boolean |
valid | function(valid){} | Function |
JsBarcode安裝:
npm install jsbarcode --save
npm install jsbarcode