[英]React.js onChange <input> tag hangs
因为我想通过输入标签获取名称。 每当我尝试输入某个值时,只输入一个字母,然后输入框进入其理想的 position。 它被挂起或卡住,我真的不明白。 我清楚这段代码在我的另一个项目中工作,所以这真的很奇怪。
const [name, setName] = useState('')
<input type='text' placeholder='Name' class='inputColor width90' name='n'
onChange={(e)=>{
setName(e.target.value)
}}
required/>
这是我的 css 上面的代码
.inputColor{
padding: 5px;
margin: 10px;
border: 0px solid;
background-color: #F0F0F0;
color: #000000;
font-size: 18px;
outline: none;
height: 35px;
}
.width90{
width: 90%;
}
但是当我在不使用onChange function的情况下运行代码时,输入框不卡不挂。 我多次检查语法,但我不知道为什么会这样。
希望有人给我最好的解决方案。
您需要添加value={name}
<input
type='text'
placeholder='Name'
class='inputColor width90'
name='n'
value={name}
onChange={(e)=> {
setName(e.target.value)
}}
required
/>
原因是如果你有一个onChange
这意味着你正在尝试动态设置值,这就是为什么你需要将value
设置为name
的值
在这里我找到了实际原因或我们对它说什么,我们无法识别它,因为它在控制台上没有显示任何错误并成功编译程序。
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>
)
}
所以,首先我在MyFunc
之外定义了name
变量和submitData
但是当我在 function 中定义它们时,挂起或卡住的错误解决了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.