【问题标题】:EmberJS Octane set focus on elementEmberJS Octane 将焦点放在元素上
【发布时间】:2020-02-03 20:16:08
【问题描述】:

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

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

到目前为止我所拥有的:

五个为什么.ts

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 }}" />

问题摘要

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

【问题讨论】:

  • 您尝试过autofocus HTML 属性吗?如果你能展示一些模板,它会更容易提供帮助!
  • @locks 我刚刚添加了一些不重要的细节

标签: javascript ember.js focus autofocus ember-octane


【解决方案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
  };
}

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

【讨论】:

    【解决方案2】:

    发现我可以在组件重新渲染后使用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-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      • 2011-01-24
      相关资源
      最近更新 更多