ReactJS 丢失元素的引用

ReactJS loosing reference of an element

我强迫元素像这样聚焦

/**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有太多的事情要做,比如它可以有右键菜单,拖动等等,所以我需要单独渲染它。

看完这篇github:

This is intended (discussed elsewhere) but rather unintuitive behavior. Every time you render:

<Value ref={(e) => { if (e) { console.log("ref", e); }}} /> You are generating a new function and supplying it as the ref-callback. React has no way of knowing that it's (for all intents and purposes) identical to the previous one so React treats the new ref callback as different from the previous one and initializes it with the current reference.

PS. Blame JavaScript :P

Source

我将代码更改为

<span id={this.props.uniqueId} ref={(c)=>
                    {if (c) { this.activeElementContainer=c; }}
                } tabIndex="0"   dangerouslySetInnerHTML={{__html: htmlToAdd}}></span>

添加 if 才是真正的改变。现在,它有一个 ref.

对于遇到此问题的其他人: 我也需要编写自定义函数,在 componentDidUpdate 中我仍然得到旧参考,

ref={(c)=>{if (c) { this.activeElementContainer=c; this.ChangeFocus(); }}

添加这个对我来说是完美的解决方案