[react] react怎么拿到组件对应的DOM元素?
- 在Class组件中
import React from 'react';
class CComponent extends React.Component {refDiv = React.createRef();componentDidMount () {console.log(this.refDiv.current)}render () {return <div><div className="test" ref={this.refDiv}>demo</div></div>}
}export default CComponent;
// 老旧语法
import React from 'react';
class CComponent extends React.Component {// refDiv = React.createRef();componentDidMount () {console.log(this.refDiv)}render () {return <div><div className="test" ref={ref => this.refDiv}>demo</div></div>}
}export default CComponent;
- 在函数式组件中
import React, { useRef, useEffect } from 'react';const FComponent = () => {const refDiv = useRef();useEffect(() => {console.log(refDiv.current);}, []);return <div><div className="demo" ref={refDiv}>test</div></div>
}
export default FComponent;
个人简介
我是歌谣,欢迎和大家一起交流前后端知识。放弃很容易,
但坚持一定很酷。欢迎大家一起讨论
主目录
与歌谣一起通关前端面试题