[Type Script] <HTML Input Element> only works as a string??? (Be careful!)

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

I am studying applying type scripts to the reader toolkit.

These are my counter components.

import React, {useState} from 'react'
import {useAppSelector, useAppDispatch} from '../app/hook'
import {decrement,increment,incrementByAmount} from '../modules/counterSlice'

export default function Counter() {
    const count = useAppSelector(state => state.counterSlice.value)
    const dispatch = useAppDispatch();

    const onIncrease = () => dispatch(increment())
    const onDecrease = () => dispatch(decrement())

    const [input, setInput] = useState<number>(0)

    const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        // // setInput(e.target.value)

    const onSubmit = (e: React.MouseEvent<HTMLButtonElement>) => {
    return (
                <button onClick={onIncrease}>+1</button>
                <button onClick={onDecrease}>-1</button>
                <input type="number" value={input} onChange={onChange}/>
                <Button onClick={onSubmit}>Add</Button>

An error occurred in setInput(e.target.value) of the onChange function!

The error is as follows:

Argument of type 'string' is not assignable to parameter of type 'SetStateAction'.ts(2345)

This means... The type of parameter in onChange is (e:React.ChangeEvent<HTMLInputElement>)

string followed by number cannot enter

How can I put the number type in the input tag?

Help me Senior artists!

Loyalty Loyalty ^^ 7

typescript react redux

2022-09-20 14:56

1 Answers

With a very high probability, typeof.target.value === 'string', the type script bounces. Test

Although HTML5 clearly has a number type input, it is essentially no different from normal input, and you should think of it as an additional option introduced for improved markup content and client implementation cosmetics. It would be nice to think of it as something like input type="email". Today, most modern browsers offer quite a few additional features to email type input, but neither type scripts nor JS provide Email types. E-mail addresses are just strings (but now the rules are a bit tricky). input type="number" is actually not much different from this.

In that sense, you can just convert it and use it.

setInput(parseFoot(e.target.value)); // The reason why parseInt is not performed is because the input property does not have step=1

2022-09-20 14:56

If you have any answers or tips

© 2022 pinfo. All rights reserved.