EmberJS Octane将焦点放在元素上

问题描述 投票:0回答:1

我具有包含多个文本区域和一个用于添加另一个文本区域的按钮的组件。当用户单击按钮时,将添加一个新的文本区域。我希望焦点移到这个新的文本区域。

我看到了this answer,但它是用于较旧的版本,我们没有在Ember中使用jQuery。

到目前为止我所拥有的:

5-whys.ts

type LocalWhy = {
  content: string;
};

export default class FiveWhys extends Component<FiveWhysArgs> {
  @tracked
  whys: LocalWhy[] = ...

  @action
  addWhy() {
    this.whys.pushObject({ content: "" });
  }
}

five-whys.hbs

{{#each this.whys as |why i|}}
  <TextQuestion @value={{why.content}} />
{{/each}}

<button {{on "click" (action this.addWhy)}}>Add Why</button>

text-question.hbs

...
<textarea value="{{ @value }}" />

问题摘要

在用户单击“添加原因”后,如何将焦点设置到新的文本区域?

javascript ember.js focus autofocus ember-octane
1个回答
1
投票

最近我做了类似的事情:

component.hbs:

{{#each this.choices as |item|}}
  {{input
    type="text"
    id=item.id
    keyPress=(action this.newElement item)
    value=(mut item.value)
  }}
{{/each}}

component.js

@action
newElement({ id }) {
  let someEmpty = this.choices.some(({ value }) => isBlank(value));

  if (!someEmpty)
    this.choices = [...this.choices, this.generateOption()];

  document.getElementById(id).focus();
}

generateOption(option) {
  this.inc ++;

  if (!option)
    option = this.store.createRecord('option');

  return {
    option,
    id: `${this.elementId}-${this.inc}`,
    value: option.description
  };
}

就我而言,我没有按钮,并且已经创建了余烬数据记录。经过一些修改,我敢打赌您可以做到!

© www.soinside.com 2019 - 2024. All rights reserved.