离子输入获取元素参考香草 js

ion-input get element reference vanilla js

我正在使用 stencil.js 创建一个与框架无关的 Web 组件,它包含一些 ionic4 Web 组件,包括 <ion-input>

ion-input 的文档显示了一种方法 getInputElement() => Promise<HTMLInputElement> 来访问本机 <input> 但我没有找到使用它来公开组件中的内部元素的正确方法.

getInputElement如何使用它?

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.css',
  shadow: true
})

export class MyComponent {    
  @Element() el: HTMLElement;
  @Prop .... ///some props
  @State ... // some state

  componentDidLoad(){}

  render() (
      <div className="foo">
        <ion-item>
          <ion-label> {this.someProp}</ion-label>
          <ion-input          
            value={this.someProp}
            clear-input={this.someProp}            
            onInput={this.handleInput} /> 
        </ion-item>
       <div>...more</div>
      </div>
    )
}

您可以使用 ref 属性获取对 JSX 元素的引用。例如:

<ion-input ref={input => this.ionInput = input}

然后在您的组件方法之一中,您可以将其作为 this.ionInput.getInputElement()

访问

https://stenciljs.com/docs/templating-jsx#getting-a-reference-to-a-dom-element

查看更多

我假设你可以使用 ref 功能做这样的事情(你可能应该输入这个):

ionInputElement;

@Element() el: HTMLElement;
@Prop .... ///some props
@State ... // some state

componentDidLoad(){
  this.ionInputElement.getInputElement().then((el) => this.el = el);
}

render() {
  return (
    <div className="foo">
      <ion-item>
        <ion-label> {this.someProp}</ion-label>
        <ion-input ref={(el) => this.ionInputElement = el}         
          value={this.someProp}
          clear-input={this.someProp}            
          onInput={this.handleInput} /> 
      </ion-item>
      <div>...more</div>
    </div>
  );
}