获取DOM

获取DOM

1、获取DOM

javascript 复制代码
import React, { PureComponent, createRef } from 'react'

export class App extends PureComponent {
	constructor() {
		super()
		
		this.titleRef = createRef()
		
		this.titleEL = null
	}

	getNativeDOM() {
		`方式1、在React元素上绑定一个ref字符串`
		console.log('ref=', this.refs.why)
		
		`方式2、使用 createRef 提前创建一个ref对象,并将其绑定到DOM元素上`
		console.log('ref=', this.titleRef.current);
		
		`方式3、在DOM上传入一个箭头函数,此DOM被渲染时,回调函数被执行,就获取到DOM了`
		console.log('this.titleEL=', this.titleEL);
	}

	render() {
		return (
			<div>
				<h2 ref="why">Hello World</h2>
				
				<h2 ref={this.titleRef}>方式2 - 你好啊</h2>
				
				<h2 ref={el => this.titleEL = el}>方式3 - 你好啊</h2>
				
				<button onClick={e => this.getNativeDOM()}>获取原生DOM</button>
			</div>
		)
	} // end-render
}

export default App

2、获取类组件实例

javascript 复制代码
import React, { PureComponent, createRef } from 'react'

`HelloWorld 组件`
class HelloWorld extends PureComponent {
	constructor() {
		super()
	}

	test() {
		console.log('我是 HelloWorld 组件中的 test方法')
	}

	render() {
		return <div>hello World</div>
	}
}


`App 组件`
export class App extends PureComponent {
	constructor() {
		super()
		
		this.hwRef = createRef()
	}

	getComponent() {
		`获取 子组件 HelloWorld 的实例`
		console.log('ref=', this.hwRef.current)
		`在这里可以调用 子组件中的方法`
		this.hwRef.current.test()
	}

	render() {
		return (
			<div>
				<HelloWorld ref={this.hwRef}></HelloWorld>
				
				<button onClick={e => this.getComponent()}>获取组件实例</button>
			</div>
		)
	}
}

export default App

3、获取函数式组件的DOM

javascript 复制代码
import React, { PureComponent, createRef, forwardRef } from 'react'

` 获取,函数式组件中的某个DOM,使用 forwardRef(props, ref) 高阶函数
  forwardRef:用于,将 ref 从父组件,透传到子组件内部的DOM元素。`
const HelloWorld = forwardRef((props, ref) => {
	return (
		<div>
			<h1 ref={ref}>函数式组件, 获取DOM</h1>
			<p>函数式组件 hello World</p>
		</div>
	)
})

export class App extends PureComponent {
	constructor() {
		super()
		this.hwRef = createRef()
	}

	getComponent() {
		console.log('ref=', this.hwRef.current)
	}

	render() {
		return (
			<div>
				<HelloWorld ref={this.hwRef}></HelloWorld>
				<button onClick={e => this.getComponent()}>获取组件实例</button>
			</div>
		)
	} // end-render
}

export default App
相关推荐
用户2986985301416 小时前
React 前端实现 Excel 与 OpenXML 双向转换:基于 WebAssembly 的浏览器端方案
javascript·react.js·excel
壹楽4 天前
用 React 19.2 的 <Activity> 做多页签保活,我踩了 6 个坑
react.js
spmcor4 天前
React useEffect 完全指南:从原理到实战的深度解析
react.js
用户298698530146 天前
React 前端实现 Word 与 OpenXML 双向转换的完整实践
javascript·react.js
月夏7 天前
我把全栈项目塞进已有 nginx 的服务器,卡我最久的是三个斜杠
nginx·react.js·docker
清晨Coding9 天前
为什么用 React Developer Tools 查看组件树这么乱?
前端·react.js
生活的囚徒10 天前
从一堆Excel到一套系统:项目管理+研发管理双门户的落地实践
react.js
ZhengEnCi12 天前
React 19 加 Vite 6 企业级前端项目目录结构:无路由 SPA、zustand 与 Tailwind 4 的分层架构指南
react.js
用户2986985301412 天前
React 前端实现 Excel 与 CSV 互转:基于 WebAssembly 的浏览器端方案
javascript·react.js·excel
Highcharts.js13 天前
Highcharts Orbit 完全指南:把每一张图表变成交互式分析工具
react.js·前端框架·highcharts·orbit·使用指南·ai 图表·交互式分析工具