现在不推荐使用 ReactDOM.findDOMNode() 的替代方法是什么? [英] what is the alternative for ReactDOM.findDOMNode() as it is deprecated now?

查看:88
本文介绍了现在不推荐使用 ReactDOM.findDOMNode() 的替代方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 findDOMNode() 的旧代码.

I have an old code which is using findDOMNode().

这是我的代码,其中 someComponent1Expand 已经导入.

Here is my code, where someComponent1 and Expand is already imported.

在这里,我有一些疑问,我用 findDOMNode() 编写的代码运行良好,但由于它现在已被弃用,我想将其删除.我浏览了许多文档,发现使用门户网站或参考文献而不是这个.我有一个理解,如果我使用 ref,那么变量 get bind 也可以访问 DOM 元素,但我想我错了,因为它以这种方式工作.有人可以纠正我对此的理解

Here I have some doubt the code I have written with findDOMNode() is working perfectly fine but as it is deprecated now I want to remove it. I have gone through many document and found to use portals or refs instead of this. I have a understanding that if I am using ref then the variable get bind to that also has an access to the DOM element, but I guess I am wrong as it is working in that way. Can someone please correct my understanding on this

class classA extends Component {

  componentDidMount() {
    new Expand(ReactDOM.findDOMNode(this.expand))
    // new Expand(this.expand)    
  }

  render(){

    return(
      <someComponent1 className={style.container} ref={e => this.expand= e}/>
    )
  }
}

推荐答案

根据 thisgithub 问题ReactDocs,ReactDOM.findDOMNode 没有被弃用,但不鼓励使用它,只能用作逃生舱口.为了替换它,您需要在 DOM 元素上指定 ref,在您的情况下,它看起来像

As per this github issue and ReactDocs,ReactDOM.findDOMNode is not deprecated but its usage is discouraged and should only be used as an escape hatch. In order to replace it, you need to specify the ref on the DOM element which in your case would look like

class classA extends Component {

  componentDidMount() {
     new Expand(this.expand)    
  }

  render(){

    return(
      <SomeComponent1 className={style.container} innerRef={e => this.expand= e}/>
    )
  }
}

class SomeComponent1 extends React.Component {
    render() {
       return <div ref={this.props.innerRef}>Hello</div>
    }
}

这篇关于现在不推荐使用 ReactDOM.findDOMNode() 的替代方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆