2017-08-30 38 views
0

我在反應應用程序中使用material-ui v1,我試圖以編程方式在TextField上調用.focus()。在TextField上使用ref屬性返回null,那麼我是如何引用TextField以在需要時調用.focus()Focus-TextField in material-ui v1

+1

如果你只是需要自動對焦,你可以做'' – FuzzyTree

+0

我沒有嘗試自動對焦,我試圖在菜單關閉時關注TextField。 – CodePB

回答

0

我認爲你可以利用參考來實現這一點。

下面是示例代碼

<input 
     ref={(input) => { this.nameInput = input; }} 
     defaultValue="will focus" 
/> 

現在正在使用裁判的,你可以進行如下

this.nameInput.focus(); 

這應該解決您的輸入框設定一個焦點問題,當其他一些事件被解僱。

+0

在material-ui的TextField控件上使用時,這不起作用。該ref返回null。必須最終以另一種方式解決這個問題。 – CodePB

+0

@CodePB我正在尋找一種方法,以編程方式在material-ui TextField上設置焦點。你能分享你如何解決這個問題嗎?提前致謝 – saadtazi

0

更新2017-09-25:在新的解決方案中,我擺脫了ReactDOM ...這是更優雅的方式。

這是我以編程方式將焦點放在material-ui TextField(v1-beta16)上的方式。

import React from 'react'; 

class MyComponent extends React.Component { 
    // you could have similar logic in 'componentDidMount' 
    componentWillReceiveProps(newProps) { 
    if (..someCondition...) { 
     // this is were the focus happens 
     this.labelField.focus();  

    } 
    } 
    render() { 
    ... 
    <TextField inputRef={field => this.textField = field} .../> 
    } 
} 

我以前下面的解決方案 - 請勿使用

這是我如何編程將焦點設置材料的UI文本字段。

import React from 'react'; 
import ReactDOM from 'react-dom'; 

class MyComponent extends React.Component { 
    // you could have similar logic in 'componentDidMount' 
    componentWillReceiveProps(newProps) { 
    if (..someCondition...) { 
     // this is were the focus happens 
     ReactDOM.findDOMNode(this.labelField).querySelector('input').focus();  

    } 
    } 
    render() { 
    ... 
    <TextField ref={field => this.textField = field} .../> 
    } 
} 

注意,我不滿意我描述這裏的解決方案,因爲它依賴於知道的TextField兒童(querySelector('input')),但主要是因爲它需要進口ReactDOM。