【问题标题】:trigger child function from parent component in stencil从模板中的父组件触发子函数
【发布时间】:2020-11-04 09:28:02
【问题描述】:

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

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

【问题讨论】:

    标签: javascript stenciljs tsx stencil-component


    【解决方案1】:

    您可以为此在子级中使用 @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)} />;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 2017-03-03
      相关资源
      最近更新 更多