首页 > 解决方案 > 从模板中的父组件触发子函数

问题描述

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

从 开始<parent-component>,我尝试运行一个函数 onClick,然后<child-component>在不使用 @Listen 装饰器的情况下将数据发送到函数中。

标签: javascriptstenciljstsxstencil-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)} />;
  }
}

推荐阅读