我正在尝试使用react-barcodes库,这真的很棒。我遇到的问题是使用钩子(必须在函数顶部无条件地声明钩子等),并且还要遍历数组以对条形码使用不同的值。我认为这比任何专门针对react-barcodes的问题都更普遍。 [here] [1]提供的示例效果很好。但是,这是我想要做的事情:
import { useBarcode } from "react-barcodes";
const BarCodeTest = (props) => {
var data = [
{
barCodeValue: "123",
},
{ barCodeValue: "456" },
];
// I want to change the "value" property here for each
const { inputRef } = useBarcode({
value: "initial value of some kind",
options: {
displayValue: true,
height: 50,
},
});
// how can I set the value property as I iterate through data[]?
return <>{data && data.map((item, index) => <svg ref={inputRef} />)}</>;
};
export default BarCodeTest;
[1]: https://github.com/Bunlong/react-barcodes#-usage
答案 0 :(得分:1)
您实际上可以将其分为两个部分,一个是您当前拥有的,另一个可以称为BarCodeItem,您可以遍历数据并将BarcodeValue作为道具发送给BarCodeItem,然后您可以像这样轻松地处理钩子下面: 这就是您通常会在反应中做的事情。
import React, { useRef } from "react";
import { useBarcode } from "react-barcodes";
const BarCodeItem = ({barcodeValue}) => {
const { inputRef } = useBarcode({
value: barcodeValue,
options: {
displayValue: true,
height: 50,
},
});
return <svg ref={inputRef} />;
};
const BarCodeTest = (props) => {
var data = [
{
barCodeValue: "123",
},
{ barCodeValue: "456" },
];
// how can I set the value property as I iterate through data[]?
return <>{data && data.map((item, index) => <BarCodeItem key={index} barcodeValue={item.barCodeValue} />)}</>;
};
export default BarCodeTest;