You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Storybook中MDX模板字面量动态HTML属性展示问题求助

解决Storybook Code面板布尔属性显示问题

问题描述

我正在开发一个基于Storybook的项目,MDX文件中的模板代码如下:

export const Template = ({dark, width, height, theme}) => {
  return html`
    <my-button
      @click=${action('button clicked')}
      width="${width}"
      height="${height}"
      theme="${theme}"
      ?dark=${dark}>
    </my-button>
  `;
};

在Controls面板将dark参数设为false时,Code面板展示的代码符合预期;但设为true时,代码显示为dark="",而我期望展示无值的dark属性(即<my-button dark>这种形式)。

解决方案

问题出在Storybook的Code面板对lit-html布尔属性语法(?dark=${dark})的解析上,它没有将布尔值正确转换为无值属性。可以通过手动条件添加属性的方式解决:

修改模板代码,直接在模板字符串中根据dark的值决定是否添加dark属性:

export const Template = ({dark, width, height, theme}) => {
  return html`
    <my-button
      @click=${action('button clicked')}
      width="${width}"
      height="${height}"
      theme="${theme}"
      ${dark ? 'dark' : ''}>
    </my-button>
  `;
};

原理说明

  • 原来的?dark=${dark}是lit-html的专属语法,用于控制布尔属性的存在性,实际DOM渲染时会正确处理,但Storybook的代码预览功能无法识别该语法,将其当作普通属性赋值处理,导致true值被转换为空字符串属性。
  • 改用条件字符串拼接后,当dark为true时,模板会直接插入dark字符串,对应HTML中的无值属性;当dark为false时,插入空字符串,不会生成该属性,完美匹配预期效果。

内容的提问来源于stack exchange,提问作者Jessica kahbjkdbv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 06:40:30