HTML 属性

Markup 模板中的 HTML 属性只是 HTML 属性。一项特定的行为更改与 布尔属性 有关,除此之外,您有关 HTML 属性的知识按原样传输。

布尔属性

HTML 中的布尔属性是表示 truefalse 值的属性。

javascript
html`
    <p hidden="false">hidden text</p>
    <button disabled>click me</button>
    <input type="checkbox" checked="false" />
`.render(document.body)
// <p hidden="false">hidden text</p>        <- still hidden
// <button disabled="">click me</button>
// <input type="checkbox" checked="false">  <- still checked

HTML 中布尔属性的问题在于,为它们提供 false 的值并不会阻止它们对元素的影响。如果它们出现在标签中,则无论其值如何,它们都具有 true 的值。

Markup 遵循 truefalse 值,并允许您仅通过指定布尔值来添加或删除这些属性。

javascript
const hidden = false
const disabled = true
const checked = false

html`
    <p hidden="${hidden}">hidden text</p>
    <button disabled="${disabled}">click me</button>
    <input type="checkbox" checked="${checked}" />
`.render(document.body)
// <p>hidden text</p>
// <button disabled="true">click me</button>
// <input type="checkbox">

将属性值设置为 false(字符串或布尔值)或 nil(undefinednull)将删除该属性。

plaintext
const disabled = false
const checked = null

html`
    <p hidden="false">hidden text</p>
    <button disabled="${disabled}">click me</button>
    <input type="checkbox" checked="${checked}" />
`.render(document.body)
// <p>hidden text</p>
// <button>click me</button>
// <input type="checkbox">

值属性

Markup 知道您在模板中作为属性值注入的值,并将相应地跟踪和更新它们。不需要额外的语法来实现这一点。

javascript
const type = 'button'
const active = 'active'
const style = 'color: white; background: black'

html`
    <button
        type="${type}"
        class="btn ${active} common"
        style="border: none; ${style}"
    >
        click me
    </button>
`.render(document.body)
// <button type="button" class="btn active common" style="border: none; color: white; background: black">click me</button>

事件属性

HTML 允许您声明内联事件属性,它们与标记的工作方式相同。添加附加事件不需要额外的语法,但 Markup 在后台执行其他操作,您可以通过阅读 events 文档了解更多信息。

javascript
const handleClick = (event) => {
    console.log(event)
}

html`<button onclick="${handleClick}">click me</button>`

参考属性

Markup 中存在而不是 HTML 中存在的一件事是 ref 属性,该属性允许您创建对元素的引用,您可以使用该引用来访问呈现的 DOM 元素以执行您需要的任何操作。您可以阅读参考文献 了解更多详细信息。

javascript
html`<button ref="btn">click me</button>`

属性作为对象

提前知道所有可能的属性是件好事,但有时这是不可能的。为此,您可以将属性收集为对象,然后根据需要注入它们作为重写。

javascript
const [count, setCount] = state(0)

const btn = ({ text = 'click me', ...props }) =>
    html` <button ${props} type="button">${text}</button>`

const countUp = () => {
    setCount((prev) => prev + 1)
}

const temp = html`
    <p>${count}</p>
    ${button({ text: '+', ariaLabel: 'count up button', onClick: countUp })}
`
/* renders:
<p>0</p>
<button type="button" aria-label="count up button">+</button>
*/

temp.render(document.body)

注入属性对象后设置的任何属性都将覆盖对象属性名称值。在上面的示例中,我们通过在注入 props 对象后设置它来确保按钮的 type 始终为 button

另外,您可以使用camelcase属性名称更改为kebab-case。在上面的示例中,当按钮呈现时,ariaLabel 将变为 aria-labelonClick 将更改为 onclick 并像事件属性 一样处理。

编辑本文档