【问题标题】:Get index of each component in Svelte slot获取 Svelte 插槽中每个组件的索引
【发布时间】:2021-07-20 09:27:53
【问题描述】:

有没有办法遍历 Svelte 组件中的所有子组件?

目标

我正在使用这种语法(理想情况下)在 Svelte 中创建一个列表组件。

<List>
  <ListItem>Item 1</ListItem>
  <ListItem>Item 2</ListItem>
  <ListItem>Item 3</ListItem>
</List>

但是,列表应该具有相当多的交互性。

  • 用户应该能够点击一个项目并选择它
  • 只有第一项应该是可标签的 (tabindex={0})
  • 用户应该能够使用箭头键/回车键来选择列表项
  • +更多与问题无关的内容

查看Material Design web components for demos

问题

为此,元素需要知道它们在列表中的“位置”。例如,第一个列表项需要知道它是第一个设置正确的tabindex。要使用箭头键导航列表,您需要知道“项目 2 处于活动状态”才能在向下箭头时切换到“项目 3”。

有没有办法遍历组件中的所有子项?

或者,一种通过组合实现 Material Design 列表行为的方法?

我知道可以通过使用数据道具而不是组合来实现这一点。但对于我的用例,从长远来看,组合可能会更好。

反应等效

如果您熟悉 React,我正在寻找类似这个极其简化的示例的东西。

const List = (props) => {
  return (
    <ul>
      {React.Children.forEach(props.children, (child, index) => (
        child.props.tabIndex = index === 0 ? 0 : -1
      ))}
    </ul>
  )
}

const ListItem = (props) => {
  return <li tabIndex={props.tabIndex}>{props.children}</li>
}

【问题讨论】:

    标签: listview material-design svelte svelte-3 svelte-component


    【解决方案1】:

    我在父级(您的 List 组件)中为下拉菜单组件使用了注册函数。

    类似:

    列表组件:

      function nested(nestedText, clicked = false) {
        if (clicked) {
          // clicked and then do something
          ...
        } else {
          // register listItem
          register = [...register, nestedText];
          return register.length - 1;  // itemIdx
        }
      }
      setContext('nested', nested);
    

    物品组件:

    let text, itemIdx, thisObj;
    const nested = getContext('nested');
    
    onMount(() => {
      text = thisObj.textContent;
      itemIdx = nested(text);  // register item
      ...
    });
    

    项目组件html:

    <a
      href="..."
      target="..."
      on:click|stopPropagation="{() => {
         nested(text, true);
      }}"
      bind:this={thisObj}>
      <slot />
    </a>
    

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 2018-06-01
      • 2021-10-16
      • 2022-01-02
      • 2021-10-07
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      相关资源
      最近更新 更多