[英]How to trigger Stencil component function/method from outside Vue instance
[英]trigger child function from parent component in stencil
如何從父組件觸發子組件功能並在 stenciljs 中發送數據
從<parent-component>
,我嘗試運行一個 onClick 函數,然后在不使用 @Listen 裝飾器的情況下將數據發送到<child-component>
函數中。
您可以在子項中使用@Method()
裝飾器:
@Component({ tag: 'child-component' })
export class Child {
@Method()
async foo() {
return 'bar';
}
}
@Component({ tag: 'parent-component' })
export class Parent {
@State() childRef?: HTMLChildComponentElement;
clickHandler = async () => {
const foo = await this.childRef?.foo();
}
render() {
return (
<Host onClick={this.clickHandler}>
<child-component ref={el => (this.childRef = el)} />
</Host>
);
}
}
請參閱https://stenciljs.com/docs/methods 。
另請注意,在呈現子項之后才設置引用(即在componentWillLoad
尚不可用)。
既然您提到了@Listen
,您可能還會發現可以將函數作為道具(有點像回調)傳遞給子級很有用。
@Component({ tag: 'child-component' })
export class Child {
@Prop() clickHandler: (e: MouseEvent) => void;
render() {
return <Host onClick={this.clickHandler} />;
}
}
@Component({ tag: 'parent-component' })
export class Parent {
render() {
return <child-component clickHandler={e => console.log(e.target.tagName)} />;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.