2017-08-05 24 views
3

如何編寫一個能夠自動選擇表單域的React組件?如何使用React JS選擇表單元素?

舉例來說,在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> 

我怎樣才能實現與反應的類似的效果?

對於某些上下文,我試圖編寫一個可編輯的表單元素,用戶可以通過單擊進行編輯,類似於此主旨中的代碼:https://gist.github.com/hanneshapke/4a12dd414a193d5406ea。但是,該要點在進入編輯模式時不會自動選擇表單域,用戶必須再次單擊以更改文本。

回答

2

不要直接操作DOM!

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

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

下面是「refs」屬性的相關文檔,這個答案引導了我。 https://facebook.github.io/react/docs/refs-and-the-dom.html –

0

要回答你的問題在代碼的背景下段,您鏈接到,我會用裁判的組合,和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; }} 
     //... 
    /> 
} 
相關問題