[英]trigger child function from parent component in stencil
How to trigger a child component function from parent component and send data in stenciljs如何从父组件触发子组件功能并在 stenciljs 中发送数据
From <parent-component>
, I am try run a function onClick and then send the data to <child-component>
in a function without using @Listen decorator.从
<parent-component>
,我尝试运行一个 onClick 函数,然后在不使用 @Listen 装饰器的情况下将数据发送到<child-component>
函数中。
You can use the @Method()
decorator in the child for that:您可以在子项中使用
@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>
);
}
}
See https://stenciljs.com/docs/methods .请参阅https://stenciljs.com/docs/methods 。
Also note that the reference is not set until after the child has been rendered (ie not yet available in componentWillLoad
).另请注意,在呈现子项之后才设置引用(即在
componentWillLoad
尚不可用)。
Since you've mentioned @Listen
, you might also find it useful that you can pass functions down to children as props (kind of like callbacks).既然您提到了
@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.