Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

javascript - 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.

question from:https://stackoverflow.com/questions/66052369/react-js-onchange-input-tag-hangs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...