Dom 当变量发生变化时,我的输入html表单会失去焦点/清空

Dom 当变量发生变化时,我的输入html表单会失去焦点/清空,dom,data-binding,scala.js,lost-focus,binding.scala,Dom,Data Binding,Scala.js,Lost Focus,Binding.scala,我想从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&

我想从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)
import com.thoughtworks.binding.\uz,binding_
导入org.scalajs.dom_
@dom def render={
val color=Var(“”)
val styleText:String=s“背景色:${color.bind}”
//并将在数据更改后重新创建。
颜色:=myInput.value}/>
}
render(document.body,render)
这个例子还在继续

但是,当我在文本框中输入内容时,文本框失去焦点,仍然保持为空


如何修复它?

也许您在相同的
@dom
方法中定义了
.bind
,并且
.bind
之后。尝试将
.bind
重构为单独的
@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)
上面的例子继续运行


另一种方法是在
@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)
import com.thoughtworks.binding.\uz,binding_
导入org.scalajs.dom_
@dom def render={
val color=Var(“”)
@dom val styleText:Binding[String]=s“背景色:${color.bind}”
//并且在数据更改时不会重新创建。
//只有class属性将被更改。
颜色:=myInput.value}/>
}
render(document.body,render)

上面的示例继续运行。

此问题和答案从
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)