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
3.9k views
in Technique[技术] by (71.8m points)

react项目,input如何在外部如何修改value值?

如何一个input

<input title="" class="input01" type="text" maxlength="6" placeholder="" pattern="d{6}" value="" inputMode="numeric">

使用JS操作

document.getElementsByClassName("input01")[0].value = 12345;

此时界面上,input框里12345会一闪而过,经过百度得知react底层可能有一个需要setstate才能通知后台渲染新数据。

请问还有什么办法可以从外部使用JS/JQ给input赋值不会被清空数据的办法吗?


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

1 Reply

0 votes
by (71.8m points)

react 项目中,最好把 input 当成受控组件,通过 setState 的方式进行值绑定,如果非要通过 js 绑定值,首先要在合适的生命周期进行原生 DOM 操作,在类组件中 componentDidMount、componentDidUpdate,函数组件中 useEffect


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

1.4m articles

1.4m replys

5 comments

57.0k users

...