【发布时间】:2020-11-04 09:28:02
【问题描述】:
如何从父组件触发子组件功能并在stenciljs中发送数据
从<parent-component>,我尝试运行一个函数onClick,然后在不使用@Listen 装饰器的函数中将数据发送到<child-component>。
【问题讨论】:
标签: javascript stenciljs tsx stencil-component
如何从父组件触发子组件功能并在stenciljs中发送数据
从<parent-component>,我尝试运行一个函数onClick,然后在不使用@Listen 装饰器的函数中将数据发送到<child-component>。
【问题讨论】:
标签: javascript stenciljs tsx stencil-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)} />;
}
}
【讨论】: