Last active
March 25, 2020 14:35
-
-
Save motionrus/8b051b9ee6513abb04ffbbdc7f086a20 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useState} from "react" | |
import './App.css'; | |
interface IBasicNumberInputProps { | |
value: number, | |
onChange: (value: number) => void, | |
} | |
function BasicNumberInput({value, onChange}: IBasicNumberInputProps) { | |
const [error, setError] = useState(""); | |
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { | |
const {value} = event.target; | |
const inputValue = Number(value) || 0 | |
onChange(inputValue); | |
}; | |
const handleKeyDown = (event: React.KeyboardEvent) => { | |
const {key} = event; | |
const $input = event.target as HTMLInputElement; | |
if (key.match(/^[a-za-я= ]$/gui)) { | |
event.preventDefault(); | |
setError("Вы ввели неверный символ") | |
} | |
if (key.match(/^\d$/gui)) { | |
if ($input.value.length > 15) { | |
event.preventDefault(); | |
setError("Количество цифр для обычного числа не может быть больше 15 знаков") | |
} | |
} | |
if (key.match(/^-$/gui)) { | |
event.preventDefault(); | |
revertSign(event) | |
} | |
}; | |
const revertSign = (event: React.KeyboardEvent) => { | |
const $input = event.target as HTMLInputElement; | |
const currentCursorPosition = $input.selectionStart as number; | |
const nextCharPosition = currentCursorPosition + 1; | |
const previousCharPosition = (currentCursorPosition === 0) ? 0 : currentCursorPosition - 1; | |
if ($input.value.startsWith("-")) { | |
$input.value = $input.value.slice(1); | |
$input.setSelectionRange( | |
previousCharPosition, | |
previousCharPosition | |
); | |
} else { | |
$input.value = `-${$input.value}`; | |
$input.setSelectionRange( | |
nextCharPosition, | |
nextCharPosition | |
); | |
} | |
onChange(Number($input.value)) | |
}; | |
return ( | |
<React.Fragment> | |
<input type="text" value={value} onChange={handleChange} onKeyDown={handleKeyDown}/> | |
<p style={{color: "red"}}>{error}</p> | |
</React.Fragment> | |
); | |
} | |
const Container = () => { | |
const [numberValue, setNumberValue] = useState<number>(0); | |
return ( | |
<div> | |
<BasicNumberInput value={numberValue} onChange={setNumberValue}/> | |
<pre>{ JSON.stringify(numberValue) }</pre> | |
</div> | |
) | |
} | |
export default Container; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment