如何从WebComponent中的onChange输入元素返回事件

时间:2019-05-16 15:09:16

标签: polymer web-component stenciljs

我想创建一个Web组件,只要输入元素中的值发生更改,该组件就会向我返回信息。我正在使用Stencil.js。

这是我的代码:

import { Component, Prop, h } from '@stencil/core';

@Component({
  tag: 'wp-input',
  styleUrl: 'input.css',
  shadow: true
})
export class InputComponent {

    @Prop() type: string = 'text';
    @Prop() disabled: boolean = false;
    @Prop() required: boolean = false;
    @Prop() labelTxt: string = '';
    @Prop() class: string = '';
    @Prop() value: string = '';
    @Prop() error: string = '';
    @Prop() id: string;
    @Prop() whenChange: Function;


  render() {
    return  (
        <div class={`wp-input-wrapper`}>
            <label htmlFor={this.id}>{this.labelTxt}</label>
            <input type="text"
                onInput={event => this.whenChange(event)}
                class={`wp-input`} id={this.id}
                value={this.value} required={this.required} />
            {this.error && <div class="error">
                {this.error}
            </div>}
        </div>
    )

  }
}

我正在我的网站上运行它

  <script>
    changeFunction = event => {
        console.log(event)
    }
  </script>

  <wp-input 
    when-change='changeFunction'
    value='i am here' error='adf' label-txt='Label text'></wp-input>

但是我仍然收到此错误:

  

wp-input.entry.js:16未捕获的TypeError:this.whenChange不是函数

是否有可能从Web组件中获取价值?还是要以某种方式通知其价值已经改变?

1 个答案:

答案 0 :(得分:0)

好的,让我回答我的问题。要将eventListener添加到CustomElement中,只需执行以下操作:

customElements.whenDefined('wp-input').then( () => {
  var input = document.querySelector("wp-input").shadowRoot.querySelector("input");

  input.addEventListener('keyup', event => {
    console.log(event.target.value)
  });
});