javascript - 从模板中的父组件触发子函数
问题描述
如何从父组件触发子组件功能并在 stenciljs 中发送数据
从 开始<parent-component>
,我尝试运行一个函数 onClick,然后<child-component>
在不使用 @Listen 装饰器的情况下将数据发送到函数中。
解决方案
您可以为此使用@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)} />;
}
}
推荐阅读
- ruby-on-rails - 如何在 Rails 的 json_response 中显示所有关联项目
- continuous-integration - VSTS build triggered twice with each push
- azure-devops - Ask for approval to change item column in Kanban in VSTS
- autohotkey - Why `run, explore` doesn't work with expression syntax?
- angular5 - Angular5 + Openlayers4 添加标记或弹出到纬度
- c++ - 窗口服务
- unity3d - How would you add some "sports field lines" on Unity Terrain?
- vba - 将 Microsoft 日期和时间选择器控件附加到 Excel 文件
- mongodb - 猫鼬大于等于
- android - How setting Clickable attribute in XML works?