1

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

我看到了这个答案,但它是针对旧版本的,我们没有将 jQuery 与 Ember 一起使用。

到目前为止我所拥有的:

五个为什么

type LocalWhy = {
  content: string;
};

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

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

五个为什么.hbs

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

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

文本问题.hbs

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

问题摘要

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

4

2 回答 2

1

这些天我做了类似的事情:

组件.hbs:

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

组件.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
  };
}

在我的情况下,我没有按钮,并且我创建了 ember 数据记录。通过一些修改,我敢打赌你可以做到这一点!

于 2020-02-10T14:55:10.750 回答
1

发现我可以Ember.run.schedule在组件重新渲染后运行代码。

@action
addWhy() {
    ... // Adding why field
    Ember.run.schedule('afterRender', () => {
      // When this function has called, the component has already been re-rendered
      let fiveWhyInput = document.querySelector(`#five-why-${index}`) as HTMLTextAreaElement
      if (fiveWhyInput)
        fiveWhyInput.focus();
    })
}
于 2020-03-13T15:17:48.650 回答