简体   繁体   中英

React.js onChange <input> tag hangs

As I want to get the name through input tag. Whenever I tried to enter some value, only one letter is type and then the input box comes into its ideal position. It is got hang or stuck, I really won't understand. I clear that this code is working in my another project so it is really weird.

const [name, setName] = useState('')

<input type='text' placeholder='Name' class='inputColor width90' name='n' 
    onChange={(e)=>{
        setName(e.target.value)
    }}
required/>

Here is my css for above code

.inputColor{
    padding: 5px;
    margin: 10px;
    border: 0px solid;
    background-color: #F0F0F0;
    color: #000000;
    font-size: 18px;
    outline: none;
    height: 35px;
}
.width90{
    width: 90%;
}

But when I run the code without using onChange function, the input box is not stuck or hang. I check the syntax as many time but I don't know why it is happening.

Hope someone gives me the best solution for this.

You need to add value={name}

<input 
    type='text' 
    placeholder='Name' 
    class='inputColor width90' 
    name='n' 
    value={name} 
    onChange={(e)=> {
        setName(e.target.value)
    }}
    required
/>

The reason is because if you have an onChange it means that you are trying to set the value dynamically, that's why you need to set the value to the value of name

Here I found the actual cause or whatever we say to it, we cannot identify it because it doesnot show any error on console and successfully compile the program.

const MyFunc = () => {

    const [name, setName] = useState('')
    
    const submitData = () => {
            Axios.post('http://localhost:3001/api/upload',{
                 n: name
            }
     }

     return (
          <div class='myCSS'>
            <table>
                <tr>
                    <td>
                        <img src={myimg} alt={myimg}/>
                    </td><td>
                        <input type='text' name='n' placeholder='Name' 
                            class='inputColor width90' 
                            onChange={(e)=>{setName(e.target.value)}}
                        required/>
                    </td><td>
                        <input type='submit' value='upload'
                             onClick={submitData}/>
                    </td>
                </tr>
            </table>
        </div>
     )
}

So, firstly I define the name variable and the submitData outside MyFunc but when I define both of them inside the function, the hang or stuck error resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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