我正在尝试在搜索栏的聚焦/模糊状态之间切换。现在,该标记具有单击处理程序,如果单击该元素,该处理程序将显示一个输入字段。我试图扭转这种影响,并在用户在元素外部单击时隐藏输入字段的可见性。
我的代码是:
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>
但是有些东西不起作用。谁能指出我做错了什么?
最佳答案
如果没有H3
属性,就不能集中tabindex
元素,因此一开始就不能对其“模糊”,因此onBlur
事件不会触发。尝试将onBlur
事件附加到input
方法中呈现的renderInput
元素上。
这是一个示例:http://plnkr.co/edit/STMPIkIQEIAZPZQ9SCq4?p=preview