Stencil同仓库组件调用:点击按钮触发my-component1并传参
问题解决方案
首先先修正你代码里的问题:my-component的render函数里嵌套了<my-component>,这会造成无限递归渲染,得先把这个嵌套去掉,比如改成这样:
// my-component.tsx render() { return ( <Host> <button onClick={this.handleClick}></button> </Host> ); }
下面给你两种实用的实现方式:
方式一:通过父组件中转(最推荐,符合组件解耦原则)
这种方式下,两个组件都放在同一个父组件中,由父组件统一管理状态和传参逻辑:
- 改造
my-component,添加点击事件发射器:
import { Component, h, Event, EventEmitter } from '@stencil/core'; @Component({ tag: 'my-component', }) export class MyComponent { @Event() componentTriggered: EventEmitter<{ data: any }>; handleClick = () => { // 点击按钮时触发事件,携带要传递的参数 this.componentTriggered.emit({ data: '你要传的参数' }); }; render() { return ( <Host> <button onClick={this.handleClick}>调用my-component1并传参</button> </Host> ); } }
- 改造
my-component1,添加接收参数的Prop:
import { Component, h, Prop } from '@stencil/core'; @Component({ tag: 'my-component1', }) export class MyComponent1 { @Prop() receivedData?: any; // 参数变化时执行逻辑处理 componentWillUpdate() { if (this.receivedData) { console.log('收到参数:', this.receivedData); // 这里写你要执行的业务逻辑 } } render() { return ( <Host> <div>我是my-component1,收到的参数:{this.receivedData}</div> </Host> ); } }
- 在父组件(比如页面或容器组件)中组合两个组件,监听事件并传递参数:
import { Component, h, State } from '@stencil/core'; @Component({ tag: 'parent-component', }) export class ParentComponent { @State() passData: any; handleTrigger = (event: CustomEvent) => { // 接收my-component传来的参数,更新状态 this.passData = event.detail.data; }; render() { return ( <Host> <my-component onComponentTriggered={this.handleTrigger}></my-component> {/* 根据状态传递参数给my-component1 */} <my-component1 receivedData={this.passData}></my-component1> </Host> ); } }
方式二:直接获取组件引用调用方法(适合组件直接关联的场景)
如果my-component1有暴露公共方法,你可以在my-component里获取它的DOM引用,直接调用方法传参:
- 改造
my-component1,添加公共方法:
import { Component, h } from '@stencil/core'; @Component({ tag: 'my-component1', }) export class MyComponent1 { // 暴露公共方法供外部调用 receiveParams(data: any) { console.log('收到参数:', data); // 执行你的业务逻辑 } render() { return ( <Host> <div>我是my-component1</div> </Host> ); } }
- 在
my-component中获取my-component1的引用,点击时调用方法:
import { Component, h, Element } from '@stencil/core'; @Component({ tag: 'my-component', }) export class MyComponent { @Element() el: HTMLElement; handleClick = () => { // 获取页面中的my-component1实例 const component1 = this.el.ownerDocument.querySelector('my-component1') as any; if (component1) { // 调用其方法并传参 component1.receiveParams('你要传的参数'); } }; render() { return ( <Host> <button onClick={this.handleClick}>调用my-component1并传参</button> </Host> ); } }
注意:方式二需要确保my-component1已经在DOM中存在,否则querySelector会获取不到。如果是动态渲染的组件,更推荐用方式一。
内容的提问来源于stack exchange,提问作者Techie
相关产品推荐
相关产品推荐

