【问题标题】:ReactJS loosing reference of an elementReactJS 失去对元素的引用
【发布时间】: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 =&gt; ( this.activeElementContainer = c) }
  • 我稍微改变了我的代码。现在可以了。

标签: javascript reactjs focus setfocus


【解决方案1】:

看完这个github:

这是有意的(在其他地方讨论过)但相当不直观 行为。每次渲染:

&lt;Value ref={(e) =&gt; { if (e) { console.log("ref", e); }}} /&gt;你是 生成一个新函数并将其作为 ref-callback 提供。反应 无法知道它是(出于所有意图和目的) 与前一个相同,因此 React 将新的 ref 回调视为 与前一个不同,并用当前初始化它 参考。

PS。怪 JavaScript :P

Source

我把代码改成了

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

添加 if 是真正的变化。现在,它有一个参考。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多