简体   繁体   English

反应 function 与 if else 语句

[英]React function with if else statements

I'm very new to React.我对 React 很陌生。 I'm trying to convert a bit of javascript into React.我正在尝试将一些 javascript 转换为 React。

It is for a barcode and I'm trying to control the width of the barcode by counting the chars in the generated string.它用于条形码,我试图通过计算生成的字符串中的字符数来控制条形码的宽度。 This code works well in JS, but only for one value.此代码在 JS 中运行良好,但仅适用于一个值。

var generatedBarcode = '1234567890' // create barcode chars
            
var charCount = (`${generatedBarcode.length}`); // count barcode chars
console.log(charCount)

        if (charCount == 9){var barcodeWidth = 2.60;}
        else if (charCount == 10){var barcodeWidth = 2.38;}
        else if (charCount == 11){var barcodeWidth = 2.24;}
        else if (charCount == 12){var barcodeWidth = 2.10;}
        else if (charCount == 13){var barcodeWidth = 1.95;}
        else if (charCount == 14){var barcodeWidth = 1.85;} // etc. I have worked out the widths
        else {var barcodeWidth = 0.75;};

I'd very much like to turn this code into a function so that I can generate multiple barcodes on a page and for each (with a different character length) work out the appropriate width.我非常想将这段代码变成 function,这样我就可以在一个页面上生成多个条形码,并为每个条形码(具有不同的字符长度)计算出合适的宽度。

If you can point me in the right direction, I'd be very grateful.如果您能指出正确的方向,我将不胜感激。 I'm desperately trying to get my head around React!我正在拼命地尝试着了解 React!

Thanks very much!非常感谢!

Add your widths to array, and just call the function that returns your width.将您的宽度添加到数组,然后只需调用返回宽度的 function。 If your barcode starts with length of 9, just change [barcode.length] to [barcode.length - 9]如果您的条形码以 9 开头,只需将[barcode.length]更改为[barcode.length - 9]

const barcodeWidths = [2.6, 2.38, 2.24, 2.1, 1.95, 1.85, ...etc.]

const getBarcodeWidth = (barcode) => {
   return barcodeWidths[barcode.length]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM