簡體   English   中英

如何在React中使用Material-UI在onFocus事件上的Textfield中選擇文本的一部分?

[英]How select part of text in a Textfield on onFocus event with material-UI in React?

我在react app中有一個帶有材料-UI TextField的模態形式,我有一個默認值es。 一個文件,當元素加載時,我只選擇文件名而不選擇擴展名。

我在標簽TextField中做了以下代碼:

<textField 
    value={value}
    fullWidth
    autoFocus
    onFocus={event => {
    event.target.select()}} />

但這將選擇textField中的所有文本。 在此處輸入圖片說明 如何只選擇一部分文字? 例如:如果我有myfile.doc,則只能選擇這樣的myfile 在此處輸入圖片說明

謝謝

setSelectionRangelastIndexOf方法結合使用以查找last的位置.

 class App extends React.Component { handleFocus = event => { event.preventDefault(); const { target } = event; const extensionStarts = target.value.lastIndexOf('.'); target.focus(); target.setSelectionRange(0, extensionStarts); } render(){ return ( <input value={'myfile.doc'} onFocus={this.handleFocus} /> ) } } ReactDOM.render(<App />, document.getElementById('root')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div> 

我將使用拆分並獲取數組的第一項。

 text = "mydoc.doc"; console.log(text.split(".")[0]); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM