2017-02-19 87 views
6

我無法自動聚焦此組件中呈現的輸入標記。我在這裏錯過了什麼?AutoFocus反應中的輸入元素JS

class TaskBox extends Component { 
    constructor() { 
    super(); 
    this.focus = this.focus.bind(this); 
    } 

    focus() { 
    this.textInput.focus(); 
    } 

    componentWillUpdate(){ 
    this.focus(); 
    } 

    render() { 
    let props = this.props; 
    return (
     <div style={{display: props.visible ? 'block' : 'none'}}> 
     <input 
     ref={(input) => { this.textInput = input; }} 
     onBlur={props.blurFN} /> 
     <div> 
      <div>Imp.</div> 
      <div>Urg.</div> 
      <div>Role</div> 
     </div> 
     <div> 
      <button>Add goal</button> 
     </div> 
     </div> 
    ) 
    } 
} 

任何幫助表示讚賞。

+0

當你呈現一個無狀態的組件,你可以添加標籤'autoFocus'到您的輸入元素,它會自動聚焦元素。 –

回答

6

有一個屬性可用於自動對焦autoFocus,我們可以使用它來自動對焦輸入元素,而不是使用ref

使用autoFocus與輸入元素:

<input autoFocus />

我們也可以使用ref,但裁判我們需要在正確的地方打電話對焦方法,你在呼喚,在componentWillUpdate生命週期的方法,該方法最初的渲染過程中不會被觸發而不是使用componentDidMount生命週期的方法,:

componentDidMount(){ 
    this.focus(); 
} 

shouldComponentUpdate:始終在渲染方法之前調用,並啓用定義是否需要重新渲染或可以跳過。顯然這種方法在初始渲染時不會被調用。只有在組件發生某種狀態變化時纔會調用它。

componentWillUpdate只要shouldComponentUpdate返回true就會被調用。

componentDidMount:只要渲染方法執行完成,就調用componentDidMount函數。可以通過此方法訪問DOM,從而可以定義DOM操作或數據獲取操作。任何DOM交互應始終發生在此。

參考:https://facebook.github.io/react/docs/react-component.html

+0

到底!我剛剛意識到這一點。它開始工作componentDidMount。爲什麼我們不能專注於componentWillUpdate?一個是渲染完成之前,另一個是發佈它,這是觸發狀態變化。 @mayank是這樣的,因爲在渲染髮生時父組件處於'display:none'模式? 所以這意味着如果我們'display:none'輸入HTML標籤,然後以編程方式聚焦它並顯示它('display:block'),則聚焦將無法工作。 我以正確的方式思考? – Ayan

+1

componentWillUpdate不會在第一次渲染時被調用,componentDidMount會在渲染後被調用,所以你需要在這個方法中關注input元素,檢查更新後的答案:) –

+1

'componentDidMount'只會在'render()在生命週期的安裝階段。所以,這只是'安裝'階段的正確方法。對於更新生命週期,這是不正確的。 –

0

設置一個ID的輸入,然後使用.setAttribute('autoFocus', true)的元素,當你想它着眼