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;
input
的focus
办法在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 区别是什么?
发表回复