【问题标题】:what is the alternative for ReactDOM.findDOMNode() as it is deprecated now?现在不推荐使用 ReactDOM.findDOMNode() 的替代方法是什么?
【发布时间】:2018-05-30 05:48:01
【问题描述】:

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

这是我的代码,其中 someComponent1 和 Expand 已经导入。

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

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}/>
    )
  }
}

【问题讨论】:

    标签: reactjs ref refs


    【解决方案1】:

    根据 this github issue 和 ReactDocs,ReactDOM.findDOMNode 并未被弃用,但不鼓励使用,只能用作逃生舱口。为了替换它,您需要在 DOM 元素上指定 ref,在您的情况下看起来像

    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>
        }
    }
    

    【讨论】:

    猜你喜欢
    • 2019-09-15
    • 2021-11-16
    • 1970-01-01
    • 2012-03-03
    • 2020-07-01
    • 2019-03-19
    • 2018-03-21
    • 1970-01-01
    • 2021-08-30
    相关资源
    最近更新 更多