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

时间:2017-08-05 01:39:22

标签: reactjs

如何编写一个自动选择表单字段的React组件?

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

<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。但是,这个要点在进入编辑模式时不会自动选择表单字段,用户必须再次单击才能更改文本。

2 个答案:

答案 0 :(得分:2)

不要直接操作DOM!

componentDidMount() {      
    this.refs.myFoo.select();       
} 

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

答案 1 :(得分:0)

要在您链接的代码段的上下文中回答您的问题,我会使用refs和setSelectionRange的组合:

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; }}
      //...
   />
}