【问题标题】:Why behavior is different?为什么行为不同?
【发布时间】:2020-04-27 17:21:57
【问题描述】:

createRef 和 ref={(c) => this.el = c} 有什么区别?

当我输出每个 ref 具有相同的元素但它不是假的。

为什么?

import React from "react"

class Home extends React.Component {
constructor(){
  super();
  this.el1 = React.createRef();
}

componentDidmount(){
  console.log(el1 === el2) // false   why false?
}

render(){
  return (
    <>
      <div ref={this.el1}>
        <span>A</span>
      </div>
      <div ref={(c)=> { this.el2 = c }}}>
        <span>A</span>
      </div>
    </>
  )
}

【问题讨论】:

  • 因为它们引用了 2 个不同的实例?为什么它们会一样?

标签: javascript reactjs use-ref create-ref


【解决方案1】:

在代码中,两个ref 都指向两个不同的DOMnodes,这就是它们不同的原因。

createRef 将返回一个 DOM 节点或组件的已安装实例,具体取决于您调用它的位置。无论哪种方式,正如您所指出的,您手头的东西确实很简单。但是如果你想用那个参考做些什么呢?如果你想在组件挂载的时候做呢?

Ref 回调非常适合,因为它们在 componentDidMount 和 componentDidUpdate 之前被调用。这就是您对 ref 进行更细粒度控制的方式。您现在不仅是命令式地抓取 DOM 元素,而是在 React 生命周期中动态更新 DOM,而是通过 ref API 对您的 DOM 进行细粒度访问。

【讨论】:

    猜你喜欢
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 2012-07-01
    • 2014-11-15
    • 2018-01-19
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多