从模具中的父组件触发子函数



如何从父组件触发子组件函数并在stenciljs 中发送数据

<parent-component>中,我尝试运行一个onClick函数,然后在不使用@Listen decorator的情况下将数据发送到函数中的<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)} />;
}
}

相关内容

最新更新