虽然三大框架的声明性渲染模型为我们抽象了大部分对 DOM 的直接操作,但在某些情况下,我们仍然需要直接访问底层 DOM 元素。
比如说在组件挂载时将焦点设置到一个 input 元素上,或在一个元素上初始化一个第三方库。这些情况就需要用到模板引用。
Angular
在 Angular 中想要引用模板中的元素,需要先定义一个模板变量,然后再在组件中使用装饰器 @ViewChild
装饰一下这个模板变量。
// 在模板中定义一个模板变量 #myInput
<input #myInput>
// 在组件类中使用 @ViewChild 装饰器来获取模板变量的引用
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
// 使用模板变量的名称作为参数
@ViewChild('myInput') myInput: ElementRef;
// 在组件类中可以使用模板变量的引用
ngOnInit() {
console.log(this.myInput.nativeElement.value);
}
}
React
在 React 中需要一个指向 DOM 节点的 ref 来实现模板引用。
import { useRef } from 'react';
export default function Form() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={handleClick}>
聚焦输入框
</button>
</>
);
}
Vue
在 Vue 中使用特殊的 ref attribute 。它允许我们在一个特定的 DOM 元素被挂载后,获得对它的直接引用。
<script setup>
import { ref, onMounted } from 'vue'
// 声明一个 ref 来存放该元素的引用
// 必须和模板里的 ref 同名
const input = ref(null)
onMounted(() => {
input.value.focus()
})
</script>
<template>
<input ref="input" />
</template>
小结
本章介绍了三大框架模板中的引用,对操作 DOM 做了介绍。
在 Angular 中,引用是通过模板变量进行操作;在 React 中,useRef
是一个 React Hook;在 Vue 中的引用方法与 React 类似。需要注意的一点时,在组件首次渲染期间引用是无效的,这是因为组件在未完成挂载前是无法识别引用的元素。
文章参考链接:
发表回复