2016-11-04 14 views
1

我有一個帶有文本輸入的React(15.3.2)組件。關注標籤點擊模糊事件後新顯示的文本輸入

(無論我說「渲染」這實際上是渲染或取消隱藏,我都試過。)

當該輸入件模糊,我渲染文本輸入一個新的組件。

我想給新的文字輸入焦點。

我試過componentDidMountcomponentWillUpdatecomponentDidUpdate;我試過命名和功能ref s;我已經嘗試了反應。

聚焦本身的作品,例如,一旦它被渲染,如果我點擊初始輸入,焦點轉到新的輸入(這是一個錯誤,但與聚焦,平凡相比)。

第一個輸入有一個onBlur,用於設置用於指示第二個輸入是否呈現的狀態。

在該模糊處理程序中,我盡我所能停止事件。

當我標籤出第一個元素時,我已經「過去了」新渲染的元素,例如我當前裸設計中的瀏覽器標籤欄–我猜這個新元素還沒有渲染?

class SecondInput extends Component { 
    componentDidUpdate = (prevProps, prevState) => { 
    if (!this.props.hidden) this._input.focus() 
    } 

    render =() => 
    <input type="text" hidden={this.props.hidden} ref={(c) => this._input = c} 
} 

class NewItem extends Component { 
    state = { itemEntered: false } 

    itemBlurred = (e) => { 
    e.preventDefault() 
    e.stopPropagation() 
    this.setState({ itemEntered: true }) 
    } 

    render =() => 
    <div> 
     Item: <input type="text" onBlur={this.itemBlurred} /> 
     <SecondInput hidden={!this.state.itemEntered} /> 
    </div> 
} 

任何想法或提示?我必須相信這是顯而易見的,因爲這肯定會一直髮生。我也開放給任何其他形式的組件層次結構,例如,如果我需要有一個容器,以某種方式包裝所有這些東西,那很好。

陣營15.3.2

回答

1

的問題,你所看到的似乎是因爲當你按Tab鍵,所以重點轉到地址欄沒有在頁面上更可聚焦元素。由於某些原因,當焦點在地址欄上時,只需撥打this._input.focus()就不會像您期望的那樣佔用焦點。

爲了解決這個問題,我添加了一個空的div,並根據是否顯示第二個輸入來設置tabIndex屬性。

爲了讓自己變得更容易,我將輸入焦點放在了mount上,而不是使用隱藏屬性。這可能會或可能不會在你的情況下工作,但它似乎更清潔,因爲如果它是一個受控輸入,它將保持從每次按鍵調用焦點的輸入。

let Component = React.Component; 
 

 

 
class SecondInput extends Component { 
 
    componentDidMount(){ 
 
    this.textInput.focus() 
 
    } 
 

 
    render(){ 
 
    return (
 
     <input type="text" ref={(input) => this.textInput = input} /> 
 
    ) 
 
    } 
 
} 
 

 
class NewItem extends Component { 
 
    state = { itemEntered: false } 
 

 
    itemBlurred = (e) => { 
 
    //e.preventDefault() 
 
    //e.stopPropagation() 
 
    this.setState({ itemEntered: true }) 
 
    } 
 

 
    render =() => 
 
    <div> 
 
     Item: <input type="text" onBlur={this.itemBlurred} /> 
 
     { 
 
     this.state.itemEntered ? [ 
 
      <SecondInput/> 
 
     ] : [] 
 
     } 
 
     <div tabIndex={this.state.itemEntered ? null : 0}/> 
 
    </div> 
 
} 
 

 
ReactDOM.render(<NewItem />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react-dom.min.js"></script>

+0

謝謝!在頁面上有多個'tabIndex = 0'會有什麼意義嗎?例如,如果頁面上有多個'NewItem'組件呢? –

+0

'tabIndex = 0'就像輸入一樣,所以你可以添加多個,但是你只需要在那裏至少有一個焦點目標在當前焦點之後。 – Mobius

+0

如果你使用隱藏方法而不是渲染表單,你可以用'tabIndex = {this.props.hidden?1:0}' – Mobius