通过ref可以去到原生节点的dom,但是封装后的组件使用ref取到的只是react对象,有没有方法取到真实的dom对象?
(我用的antd,想要取到 的真实dom,只能取到react对象,通过document可以取到,findDomNode我也试了,取到的是空,想问问有什么react的方法)
React获取真实dom
gitHber
#1
oyb81076
#5
import React, { Component } from 'react';
import ReactDOM from "react-dom";
import "antd/lib/button/style"
import Button from "antd/lib/button/button"
class App extends Component {
rootRef = React.createRef();
btnRef = React.createRef();
render() {
return (
<div className="App" ref={this.rootRef}>
<Button ref={this.btnRef}>Button</Button>
</div>
);
}
componentDidMount() {
console.log(this.rootRef.current instanceof HTMLElement)
console.log(ReactDOM.findDOMNode(this.btnRef.current) instanceof HTMLElement)
}
}
export default App;
虽然不知道你想要拿到原生dom干什么,但是ReactDOM.findDOMNode都不是什么好的方式,
推荐还是在 antd的组件外面包一层 div, 然后用ref然后在外面这曾组件上进行你想要的操作,就算想要获取 antd的原生组件,也还是可以通过 this.rootRef.current.children[0]这样子的操作,
因为像这种组件
function Frag(){
return <><div>A</div><div>B</div></>
}
用ReactDOM.findDOMNode 我也不知道找出来的是什么东西,会不会有bug
gitHber
#6
你说的我试了一遍,this.rootRef.current.children[0] 只能获取到html 标签的,像< div />,但是 < MyDiv />这种通过ref取到的只能是react对象,除非< MyDiv />内部有ref,那么可以通过this.rootRef.current.refs去取到