2015-09-06 69 views
2

我試圖在搜索欄的焦點/模糊狀態之間切換。現在標籤有一個點擊處理程序,如果單擊該元素,它將顯示一個輸入字段。我試圖扭轉這種效果,並在用戶單擊元素外部時隱藏輸入字段的可見性。反應 - 如何更改焦點/模糊事件的點擊狀態

我的代碼是:

var Search = React.createClass({ 

    getInitialState:function(){ 
    return{ inputVisible:false } 
    }, 
    showInput:function(){ 
    this.setState({ inputVisible:true }); 
    }, 
    componentDidUpdate:function(){ 
    if(this.state.inputVisible){ 
     this.getDOMNode().focus(); 
    } 
    }, 
    renderInput: function(){ 
    return ( 
     <input type="text" style={this.props} /> 
    ); 
    }, 
    renderLink: function(){ 
    return (
     <a><h3 onClick={this.showInput}>Search</h3></a> 
    ); 
    }, 
    render: function() { 
    if(this.state.inputVisible){ 
     return this.renderInput(); 
    }else{ 
     return this.renderLink(); 
    } 
    } 
}); 

我試着添加邏輯到componentDidUpdate功能,使

if (input.state.isVisible == false) { 
    this.getDOMNode().blur(); 
} 

我也嘗試添加的onblur處理程序的元素,並試圖創造hideInput方法:

hideInput: function() { 
    this.setState({ inputVisible:false }); 
} 

並添加到元素:

<a><h3 onClick={this.showInput} onBlur={this.hideInput}>Search</h3></a> 

但是有些東西不起作用。任何人都可以指出我做錯了什麼?

回答

2

您不能集中H3元素而沒有tabindex屬性,因此它不能被「模糊」開始,因此onBlur事件不會觸發。嘗試在renderInput方法中的input元素上附加onBlur事件。

下面是一個例子:http://plnkr.co/edit/STMPIkIQEIAZPZQ9SCq4?p=preview

+0

好的!那是爲我做的,謝謝! – amoeboar