【发布时间】:2018-03-14 12:20:30
【问题描述】:
我强迫元素像这样聚焦
/**focusing the element if the element is active */
componentDidUpdate() {
console.log(this.activeElementContainer);
if(this.activeElementContainer!==undefined && this.activeElementContainer!==null) {
/** need to focus the active elemnent for the keyboard bindings */
this.activeElementContainer.focus();
}
}
我的渲染有条件渲染,元素是从数组中动态渲染的,
假设我在 div 中有一个元素,我正在从工具箱中添加另一个元素。在这种情况下,我需要关注我拖动的最后一个元素。
render() {
let childControl= <span tabIndex="-1" dangerouslySetInnerHTML={{__html: htmlToAdd}}></span>;
if(this.props.activeItem){
childControl=<span ref={ (c) => this.activeElementContainer = c }
tabIndex="0" dangerouslySetInnerHTML={{__html: htmlToAdd}}></span>
}
//later I ma using childControl to array and it works fine.
日志说,第一次运行良好
但是,this.activeElementContainer 第二次是undefined
是否有任何替代方法或可能的解决方案?
问题是我一次只需要关注一个元素。
记住:Activecontrol 有太多的事情要做,比如它可以有右键菜单、拖动等,所以我需要单独渲染它。
【问题讨论】:
-
尝试将 ref 更改为
ref={ c => ( this.activeElementContainer = c) } -
我稍微改变了我的代码。现在可以了。
标签: javascript reactjs focus setfocus