简体   繁体   中英

trigger child function from parent component in stencil

How to trigger a child component function from parent component and send data in stenciljs

From <parent-component> , I am try run a function onClick and then send the data to <child-component> in a function without using @Listen decorator.

You can use the @Method() decorator in the child for that:

@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>
    );
  }
}

See https://stenciljs.com/docs/methods .

Also note that the reference is not set until after the child has been rendered (ie not yet available in componentWillLoad ).


Since you've mentioned @Listen , you might also find it useful that you can pass functions down to children as props (kind of like callbacks).

@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)} />;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM