现在不推荐使用 ReactDOM.findDOMNode() 的替代方法是什么?

what is the alternative for ReactDOM.findDOMNode() as it is deprecated now?

我有一个旧代码正在使用 findDOMNode()

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

这里我有点怀疑我用 findDOMNode() 编写的代码是否工作得很好,但因为它现在已被弃用,所以我想删除它。我浏览了许多文档,发现可以使用 portals 或 refs 而不是这个。 我有一个理解,如果我使用 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}/>
    )
  }
}

根据 this github issue and ReactDocsReactDOM.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>
    }
}