ReactJS-如何在ReactJS类组件中自动对具有可满足属性为true的元素自动对焦?
我在正在从事的项目中发现了这个P标签。这是我前端的输入字段。我并不是那么熟悉的p tag是一个输入字段,但是当我的组件加载时,我只是要在此p标签输入字段中自动将文本量放置,因此用户始终准备键入并知道在哪里输入。
<div className="create-post">
<p
contentEditable={!this.props.isLoading}
spellCheck="true"
placeholder="Write a new post here"
id="txtContent"
onKeyUp={this.entSub}
onDrop={this.dropDrag}
></p>
</div>
我尝试仅将 autocous
作为p标签添加,但什么也没有发生。我想这仅在实际HTML输入字段中起作用。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将需要使用
refs
( useref useref hook )&amp;然后只需inputref.current.focus();
。棘手的部分是如何将商人移至最后?
完整代码
完整的示例 on codesandbox
You will need to use
refs
(useRef hook) & then simplyinputRef.current.focus();
.Tricky part is how to move the caret to the end?
Full code
Complete example on Codesandbox
请参阅评论以获取说明,请询问您是否有任何疑问。
另请注意,与
p
标签相比span
div 标签可能会有更多运气>。行为可能会因浏览器而异。See comments for explanation, and please ask if you have any questions.
Also note, you may have more luck with a
span
ordiv
tag than ap
tag when it comes tocontentEditable
. Behavior may vary across browsers.要使元素焦点,您可以简单地使用HTML标签
Tabindex
(在React,Tabindex
中):Tabindex
接受整数值。值0意味着该元素在任何正值后都应集中。当负(确切值无关紧要)时,这意味着该元素无法通过顺序键盘达到。当阳性时,这意味着该元素应基于数字值定义的顺序(3在4之前焦点,依此类推)。有关更多信息,您可以检查
To make an element focusable, you can simply use the html tag
tabindex
(in React,tabIndex
):tabindex
accepts an integer value. The value 0 means that the element should be focusable after any positive values. When negative (the exact value doesn't matter), it means that the element is not reachable via sequential keyboard. When positive, it means that the element should be focusable based on an order defined by the value of the number (3 is focusable before 4, and so on and so forth.).For more, you can check the official doc