【问题标题】:How to self reference Astro component如何自引用 Astro 组件
【发布时间】:2022-11-11 15:42:01
【问题描述】:

我有这个组件 Astro 组件(位于“src/components/Menu.astro”);

---
export interface MenuItem {
  name: string;
  link: string;
  items?: MenuItem[];
}

export interface Props {
  items: MenuItem[];
  depth: number;
}

const { items, depth } = Astro.props;
---

<ul data-depth={depth}>
  {
    items.map(({ name, link, items: subItems }) => {
      if (subItems && subItems.length > 0) {
        return (
          <li>
            <div class="dropdown">
              {link ? <a href={link}>{name}</a> : <button>{name}</button>}

              <Menu items={subItems} depth={depth + 1} />
            </div>
          </li>
        );
      }

      return (
        <li>
          <a href={link}>{name}</a>
        </li>
      );
    })
  }
</ul>

在第 28 行(该行显示为&lt;Menu items={subItems} depth={depth + 1} /&gt;)抛出一个错误说;

ReferenceError:未定义菜单

在这种情况下,我如何自我引用 Astro 组件?提前致谢。

PS:“菜单”是组件文件的名称。

【问题讨论】:

    标签: astrojs


    【解决方案1】:

    在前面,即在两个--- 之间,你写import Menu from "./Menu.astro"

    你会得到新的错误,因为你不能在正文中使用语句。

    改变

    items.map(({ name, link, items: subItems }) => {
          if (subItems && subItems.length > 0) {
            return (
              <li>
                <div class="dropdown">
                  {link ? <a href={link}>{name}</a> : <button>{name}</button>}
    
                  <Menu items={subItems} depth={depth + 1} />
                </div>
              </li>
            );
          }
    
          return (
            <li>
              <a href={link}>{name}</a>
            </li>
          );
        })
    

    items.map(({ name, link, items: subItems }) => 
          (subItems && subItems.length > 0)
            ? <li>
                <div class="dropdown">
                  {link ? <a href={link}>{name}</a> : <button>{name}</button>}
    
                  <Menu items={subItems} depth={depth + 1} />
                </div>
              </li>
    
           : <li>
              <a href={link}>{name}</a>
            </li>
        )
    

    【讨论】:

      猜你喜欢
      • 2022-08-24
      • 2022-08-18
      • 2022-09-26
      • 2022-12-30
      • 2023-01-25
      • 2023-01-16
      • 2022-11-20
      • 1970-01-01
      • 2023-02-08
      相关资源
      最近更新 更多