首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用React JS选择表单元素?

问如何使用React JS选择表单元素?
EN

Stack Overflow用户
提问于 2017-08-05 09:39:22
回答 2查看 733关注 0票数 3

如何编写自动选择表单域的React组件?

例如,在jQuery中,您可以使用select()自动选择表单域

代码语言:javascript
复制
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>select demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
  <input type="text" name="foo" value="Some text">
<script>
  $("input").select();
</script>
</body>
</html>

如何使用React实现类似的效果?

对于某些上下文,我正在尝试编写一个可编辑的表单元素,用户可以通过单击它来对其进行编辑,类似于下面的代码:https://gist.github.com/hanneshapke/4a12dd414a193d5406ea。但是,当表单域进入编辑模式时,此gist并不会自动选择它,用户必须再次单击才能更改文本。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-05 10:31:11

不要直接操作DOM!

代码语言:javascript
复制
componentDidMount() {      
    this.refs.myFoo.select();       
} 

render() {   
    return (
        <div>              
            <input ref="myFoo" type="text" value="123"/>
        </div>             
    );                     
}
票数 2
EN

Stack Overflow用户

发布于 2017-08-05 10:07:12

为了在您链接的代码片段的上下文中回答您的问题,我将使用ref和setSelectionRange的组合:

代码语言:javascript
复制
handleEdit (e) {
    this.textInput.setSelectionRange(0, this.textInput.value.length)
    return (e) => this.setState({
      editing: !this.state.editing
    });
  }

render() {
   //...

   // setting the ref on render...
   <input
      type="text"
      ref={(input) => { this.textInput = input; }}
      //...
   />
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45517427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档