关于react.js:findDOMNode与ref的区别

8次阅读

共计 1535 个字符,预计需要花费 4 分钟才能阅读完成。

ref增加到组件上获取的是组件(只能是类组件,因为函数组件没有实例)的实例,增加到原生 HTML 元素上获取的是DOM

fondDOMNode当参数是 DOM 时失去的也是 DOM,这个没有什么作用,应用ref 就能够了。当参数时组件实例时获取的是组件 render 返回的DOM

上面举些例子验证 findDOMNode 性能是否如下面所说,ref的介绍能够参考 react 如何应用 ref

1、参数是DOM

import React, {useEffect} from 'react';
import {findDOMNode} from 'react-dom';


const FindDOMNode = () => {const inputRef = React.createRef<HTMLInputElement>();

  useEffect(() => {if (inputRef.current) {const inputDOM = findDOMNode(inputRef.current);
      console.log(inputDOM, inputRef.current)
    }
  })

  return <input type="text" ref={inputRef}/>
}

export default FindDOMNode;


控制台打印发现 findDOMNode 参数是 DOM 返回还是参数 DOM,这种应用没有什么意义,个别也不举荐这样应用,间接应用ref 即可

咱们加上一行代码使 input 聚焦,发现 findDOMNode 返回的 Element 类型的DOM

export function findDOMNode(instance: ReactInstance | null | undefined): Element | null | Text;

inputfocus 办法在 HTMLInputElement 类型的 DOM 对象上,而 HTMLInputElement 类型继承了 Element,咱们只须要应用as 断言成理论类型即可

const inputDOM = findDOMNode(inputRef.current) as HTMLInputElement;
inputDOM.focus()

ref.current返回的就是咱们 React.createRef<HTMLInputElement>()定义好的泛型类型

2、参数是Component

// 父组件
import React, {useEffect} from 'react';
import {findDOMNode} from 'react-dom';
import InputComp from './inputComp';


const FindDOMNode = () => {

  // InputComp 指明组件实例的类型
  const inputRef = React.createRef<InputComp>();

  useEffect(() => {if (inputRef.current) {const inputDOM = findDOMNode(inputRef.current);
      console.log(inputDOM, inputRef.current)
    }
  })

  return <InputComp ref={inputRef}></InputComp>
}

export default FindDOMNode;

// 子组件
import React from 'react';


class InputComp extends React.Component<{}, {}> {render() {
    return <div>
      <input type="text"/>
    </div>
  }
}

export default InputComp;

控制台打印状况恰好验证了结尾说的

参考文章:this.refs 和 ReactDOM.findDOMNode 区别是什么?

正文完
 0