首页 > 解决方案 > 如何在 stenciljs 中调用第三方组件的方法

问题描述

我在我的 stencilJs 应用程序中使用这个库中的 LottiePlayer

在他们提到的文档中:

您也可以以编程方式设置和加载动画。

</lottie-player>
const player = document.querySelector("lottie-player");
player.load("https://assets3.lottiefiles.com/packages/lf20_UJNc2t.json");

// or load via a Bodymovin JSON string/object
player.load(
 '{"v":"5.3.4","fr":30,"ip":0,"op":38,"w":315,"h":600,"nm":"new", ... }'
);

现在在我的模板组件中,我正在做

import * as lottiePlayer from "@lottiefiles/lottie-player";


@Component({
    tag: "welcome-page",
    styleUrl: "welcome-page.scss",
    shadow: true,
})
export class WelcomePage {
    private lottie: lottiePlayer.LottiePlayer;

    animate(): void {
        console.log(this.lottie);
        this.lottie.load("https://assets3.lottiefiles.com/packages/lf20_UJNc2t.json");
    }

    render(): any {
        return (
            <Host>
               <lottie-player
                    ref={(el) => this.lottie = el}
                    autoplay
                    mode="normal"
                    style={{ width: "300px", height: "300px" }}
                >
                </lottie-player>
                <idv-button
                            buttonType="primary"
                            onClick={this.animate.bind(this)}>
                            Animate
                </idv-button>
             </Host>
          );
      }

当我运行时,我得到一个对 html 元素的引用,但它不是 LottiePlayer 的类型,我可以在它上面调用一个方法。

在此处输入图像描述

我也这样做了,但播放器为空

    animate(): void {
        const player: lottiePlayer.LottiePlayer = document.querySelector("lottie-player");
        player.load("https://assets3.lottiefiles.com/packages/lf20_UJNc2t.json");
    }

我该如何解决这个问题?

标签: web-componentstenciljs

解决方案


我这样解决了,以防其他人有同样的问题


    @Element() el;

    ...
  
    animate(): void {
        let element: any = this.el.shadowRoot.querySelector("lottie-player");

        if (element) {
            element.load("https://assets3.lottiefiles.com/packages/lf20_UJNc2t.json");
        }
    }

推荐阅读