当 Var 更改时,我的输入 html 表单会丢失焦点/清空



我想从Binding.scala创建一些UI。UI 包含一个文本框。当用户在文本框中键入文本时,我想根据用户输入更改背景颜色。

import com.thoughtworks.binding._, Binding._
import org.scalajs.dom._
@dom def render = {
  val color = Var("")
  val styleText: String = s"background-color: ${color.bind}"
  // <div> and <input> will be recreated once data changes.
  <div style={styleText}>
    <input id="myInput" type="text" oninput={ _: Any => color := myInput.value }/>
  </div>
}
dom.render(document.body, render)

该示例在 ScalaFiddle 上运行。

但是,当我在文本框中输入某些内容时,文本框会错过焦点并且仍然保持空白。

我该如何解决它?

也许您在相同的@dom方法中定义了<input ...>.bind,并且<input ...>.bind之后。尝试重构.bind<input ...>到单独的@dom方法中,或者让.bind表达式嵌套在另一个 DOM 中。


例如,如果在 .bind 之前写入myInput,则不会重新创建它:

import com.thoughtworks.binding._, Binding._
import org.scalajs.dom._
@dom def render = {
  val color = Var("")
  val myInput = <input id="myInput" type="text" oninput={ _: Any => color := myInput.value }/>
  val styleText: String = s"background-color: ${color.bind}"
  // <div> will be recreated once data changes.
  // <input> will not be recreated.
  <div style={styleText}>
    {myInput}
  </div>
}
dom.render(document.body, render)

上面的例子在ScalaFiddle上运行。


如果.bind表达式嵌入在 XHTML 文本中,则不会影响其子项:

import com.thoughtworks.binding._, Binding._
import org.scalajs.dom._
@dom def render = {
  val color = Var("")
  // <div> and <input> will not be recreated when data changes.
  // Only the class attribute will be changed.
  <div style={s"background-color: ${color.bind}"}>
    <input id="myInput" type="text" oninput={ _: Any => color := myInput.value }/>
  </div>
}
dom.render(document.body, render)

上面的例子在ScalaFiddle上运行。


另一种方法是将表达式包装在@dom val.bind

import com.thoughtworks.binding._, Binding._
import org.scalajs.dom._
@dom def render = {
  val color = Var("")
  @dom val styleText: Binding[String] = s"background-color: ${color.bind}"
  // <div> and <input> will not be recreated when data changes.
  // Only the class attribute will be changed.
  <div style={styleText.bind}>
    <input id="myInput" type="text" oninput={ _: Any => color := myInput.value }/>
  </div>
}
dom.render(document.body, render)

上面的例子在ScalaFiddle上运行。

最新更新