从模具中的父组件触发子功能

问题描述

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

我尝试从bulma开始运行onClick函数,然后在不使用@Listen装饰器的情况下将数据发送到<parent-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)} />;
  }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...