gpt4 book ai didi

javascript - Stenciljs @Method 不工作

转载 作者:数据小太阳 更新时间:2023-10-29 05:51:15 25 4
gpt4 key购买 nike

我正在努力让 stenciljs 中的 @Method 正常工作 - 我们将不胜感激。

这是我的组件代码,其中包含一个名为 setName 的函数,我想在我的组件上公开它:

import { Component, Prop, Method, State } from "@stencil/core";

@Component({
tag: "my-name",
shadow: true
})
export class MyComponent {

@Prop() first: string;
@Prop() last: string;
@State() dummy: string;

@Method() setName(first: string, last: string): void {
this.first = first;
this.last = last;
this.dummy = first + last;
}
render(): JSX.Element {
return (
<div>
Hello, World! I'm {this.first} {this.last}
</div>
);
}
}

这是引用该组件的 html 和脚本:

<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
<title>Stencil Component Starter</title>
<script src="/build/mycomponent.js"></script>

</head>
<body>

<my-name />

<script>
var myName = document.querySelector("my-name");
myName.setName('Bob', 'Smith');
</script>
</body>
</html>

这是我遇到的错误的屏幕截图,它是Uncaught TypeError: myName.setName is not a function:

enter image description here

最佳答案

组件上的方法不是立即可用的;在您使用它们之前,它们必须由 Stencil 加载/水合。

组件有一个 componentOnReady 函数,可以在组件准备好使用时解析。所以像这样:

var myName = document.querySelector("my-name");
myName.componentOnReady().then(() => {
myName.setName('Bob', 'Smith');
});

关于javascript - Stenciljs @Method 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50272576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com