enfant terrible of HTML inputs. Complaints about this input are numerous.
Number input problems
Inconsistency. Different browsers handle them differently. You can enter only numbers in Chromium based browsers. But you can enter any symbol in Firefox and Safari, though they will show an error popup.
Complexity. Valid numbers are not just digits. Number input allows negative (-100) and floating point (0.01) values, as well as scientific notation (-2.3e4). Which is helpful sometimes, but not every time.
Unexpected behavior. Number input will not report the value it considers invalid. Blank string is reported instead. Also, values which have more significant digits than step attribute are considered invalid.
Fortunately, HTML allows us to fix most of these problems. So let's create a better number input. Here is the list of basic features to support.
Numeric input features
Validates user input in all modern browsers consistently.
Sets the decimal input mode for on-screen keyboards.
Can increment and decrement when up or down keys pressed.
Setting input attributes
First thing, we apply native input attributes in order to make it function like we want. I'm going to use pattern attribute to sanitize user's text input.
Available patterns
(?:0|[1-9]\d*) - Allow only digits, 1234567890
[+\-]?(?:0|[1-9]\d*) - Allow positive and negative integers, e.g. 1, -2, +3
[+\-]?(?:0|[1-9]\d*)(?:\.\d+)? - Allow floating integers, e.g. 1.001, -123.9
[+\-]?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)? - Allow scientific notation, e.g. -1.314e12
Here is how our HTML should look like now.
<input type="text" pattern="(?:0|[1-9]\d*)" inputMode="decimal" autoComplete="off"/> </p> <p>inputMode="decimal" sets proper keyboard for touch devices.</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172666848629122.jpg" class="lazy" alt="Let"></p> <p>autoComplete="off" is needed to disable annoying browser autocomplete, usually such functionality is needed for name-like inputs. </p> <h2> React component interface </h2> <pre class="brush:php;toolbar:false">// List of available numeric modes enum Modes { natural = 'natural', integer = 'integer', floating = 'floating', scientific = 'scientific', } type Value = string; export type Props = { /** Set controlled value */ value?: Value; /** Provide a callback to capture changes */ onChange?: (value?: Value) => void; /** * Define a number to increase or decrease input value * when user clicks arrow keys */ step?: number; /** Set a maximum value available for arrow stepping */ max?: number; /** Set a minimum value available for arrow stepping */ min?: number; /** Select a mode of numeric input */ mode?: keyof typeof Modes; }; export const InputNumeric: FC<Props> = ({ value, step = 1, max = Infinity, min = -Infinity, onChange = () => {}, mode = Modes.scientific, }) => { //... }
Now we need to manage pattern attribute according to the mode setting.
const patternMapping = { [Modes.natural]: '(?:0|[1-9]\\d*)', [Modes.integer]: '[+\\-]?(?:0|[1-9]\\d*)', [Modes.floating]: '[+\\-]?(?:0|[1-9]\\d*)(?:\\.\\d+)?', [Modes.scientific]: '[+\\-]?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+\\-]?\\d+)?', }; const pattern = patternMapping[mode];
Handle keystrokes
Here is how to handle arrow key presses.
const handleKeyDown = useCallback( (event: KeyboardEvent<HTMLInputElement>) => { const inputValue = (event.target as HTMLInputElement).value; // handle increment if (event.key === 'ArrowUp') { // empty input value has to be normalized to zero const nextValue = Number(inputValue || 0) + step; if (nextValue <= max) { onChange(nextValue.toString()); } } // handle decrement if (event.key === 'ArrowDown') { const nextValue = Number(inputValue || 0) - step; if (nextValue >= min) { onChange(nextValue.toString()); } } }, [max, min, onChange, step] );
User input validation
We are going to inform user about expected number format violations via input border color and option hint below input.
We are going to use Tailwind CSS to create this design and error reporting functionality.
peer class name is necessary to create a CSS selector for an input error message below. invalid:border-red-600 class name paints border with red color when input is invalid.
invisible class sets visibility:hidden for the hint message by default. peer-[:invalid]:visible class unwraps to the following selector .peer:invalid ~ .peer-\[\:invalid\]\:visible which makes hint visible when it's preceded by the input.peer in :invalid state.
export const InputNumeric: FC = () => { const id = useId(); return ( <fieldset> <label htmlFor={id}> Numeric input </label> <input id={id} className="peer invalid:border-red-600" aria-describedby={`${id}-helper-text`} /> <div className="invisible peer-[:invalid]:visible" id={`${id}-helper-text`}> Please provide valid decimal number </div> </fieldset> ); }
Here is full Numeric input code:
Happy coding!
以上是Let&#s create a better Number Input with React的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

因此,在这里,您准备好了解所有称为Ajax的东西。但是,到底是什么? AJAX一词是指用于创建动态,交互式Web内容的一系列宽松的技术。 Ajax一词,最初由Jesse J创造

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

本文讨论了使用浏览器开发人员工具的有效JavaScript调试,专注于设置断点,使用控制台和分析性能。

将矩阵电影特效带入你的网页!这是一个基于著名电影《黑客帝国》的酷炫jQuery插件。该插件模拟了电影中经典的绿色字符特效,只需选择一张图片,插件就会将其转换为充满数字字符的矩阵风格画面。快来试试吧,非常有趣! 工作原理 插件将图片加载到画布上,读取像素和颜色值: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data 插件巧妙地读取图片的矩形区域,并利用jQuery计算每个区域的平均颜色。然后,使用

本文将引导您使用jQuery库创建一个简单的图片轮播。我们将使用bxSlider库,它基于jQuery构建,并提供许多配置选项来设置轮播。 如今,图片轮播已成为网站必备功能——一图胜千言! 决定使用图片轮播后,下一个问题是如何创建它。首先,您需要收集高质量、高分辨率的图片。 接下来,您需要使用HTML和一些JavaScript代码来创建图片轮播。网络上有很多库可以帮助您以不同的方式创建轮播。我们将使用开源的bxSlider库。 bxSlider库支持响应式设计,因此使用此库构建的轮播可以适应任何

数据集对于构建API模型和各种业务流程至关重要。这就是为什么导入和导出CSV是经常需要的功能。在本教程中,您将学习如何在Angular中下载和导入CSV文件


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Dreamweaver CS6
视觉化网页开发工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。