8.2 HTML Attributes 与 DOM Properties
HTML Attributes 的作用是设置与之对应的 DOM Properties 的初始值;分不清两者,就写不对属性设置逻辑。
一、两个概念的区分
以 <input id="my-input" type="text" value="foo" /> 为例:
| 概念 | 含义 | 例子 |
|---|---|---|
| HTML Attributes | 定义在 HTML 标签上的属性 | id="my-input"、type="text"、value="foo" |
| DOM Properties | 用 JavaScript 读取 DOM 对象得到的属性 | el.id、el.type、el.value |
两者的对应关系可以归为三类:
| 关系 | 例子 | 说明 |
|---|---|---|
| 直接映射 | id → el.id | 名字相同,值也相同 |
| 名字不同 | class → el.className | 仍是映射关系,但名字不一样 |
| 没有对应 | aria-* 只有 Attribute;el.textContent 只有 Property | 一边有、另一边没有 |
理解二者的差异与关联,既关系到如何合理地设计虚拟节点的结构,也是正确地为元素设置属性的关键。
二、value:初始值与当前值
<input id="my-input" type="text" value="foo" onchange="change()" />
const el = document.querySelector('#my-input')
console.log(el.value) // 'foo'
function change() {
// 用户改为 'bar' 后再看这三个值
console.log(el.getAttribute('value')) // 'foo' —— 仍是初始值
console.log(el.value) // 'bar' —— 当前值
console.log(el.defaultValue) // 'foo' —— 初始值
}
由此得出几条结论:
- HTML Attributes 负责提供初始值;一旦值改变,DOM Properties 始终存储当前值,而
getAttribute得到的仍是初始值; - 一个 HTML Attribute 可能关联多个 DOM Properties(
value关联el.value与el.defaultValue); - 如果 HTML Attributes 提供的默认值不合法,浏览器会使用内建的合法值作为对应 DOM Properties 的默认值。
一句话:Attribute 管「初始值」,Property 管「当前值」。
三、这对渲染器意味着什么
- 模板里写的是
props(写法上更接近 HTML Attributes),但渲染时应该优先设置 DOM Properties; - 哪些 key 走 DOM Properties、哪些只能走
setAttribute,就落到 8.3 正确地设置元素属性 要解决的问题上。
相关
- 8.1 挂载子节点和元素的属性:属性渲染的第一版实现
- 8.3 正确地设置元素属性:
shouldSetAsProps的取舍