【问题标题】:How to verify if prop passed is a Component type in Svelte?如何验证传递的道具是否是 Svelte 中的组件类型?
【发布时间】:2019-12-31 08:08:57
【问题描述】:

我有一个支持functionComponent 的道具。所以我想通过检查道具的类型来区分它是组件还是函数。我目前正在使用以下一个。当代码被混淆时,这可能在 prod 中不起作用。想知道更好的解决方案吗?

let isSvelteComponent = component => {
    return (
      typeof component !== "undefined" &&
      component.__proto__.name === "SvelteComponentDev"
    );
  };

【问题讨论】:

    标签: svelte svelte-3 svelte-component


    【解决方案1】:

    我认为,宽泛地说,任何函数都可能是有效的 Svelte 组件:

    <script>
        import B from './B.svelte'
    
        const C = function(opts) {
            return new B(opts)
        }
    </script>
    
    <B />   
    
    <C />
    

    REPL

    因此,实际上并没有一种完全可靠的方法可以将 Svelte 组件与常规函数区分开来。

    在您的情况下,如果 Svelte 组件和函数具有不同的含义并且应该以不同的方式处理,也许它们应该通过不同的道具传递?这样可以确定什么是什么,以及它的用途。

    【讨论】:

      【解决方案2】:

      我可以通过检查原型来解决这个问题

      import { SvelteComponent } from "svelte";
      let isSvelteComponent = component => {
         return SvelteComponent.isPrototypeOf(component);
      };
      

      【讨论】:

      • 似乎有效!您是否遇到过此测试可能失败的极端情况?作为记录,我使用 return Object.prototype.isPrototypeOf.call(SvelteComponent, component);,根据我的 ESLint 建议!
      • 备案,这种检查是通过代码缩小丢失的。直到今天,我还没有可靠的方法来区分 Svelte 组件。
      猜你喜欢
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 2020-03-22
      • 2020-04-09
      • 1970-01-01
      • 2020-06-19
      相关资源
      最近更新 更多