Scala.js 如何在scalsjs react中获取组件的引用?
这个医生 有点不清楚 我创建了一个小示例:“squareViewer”通过单击显示“square” 如何在方法squareViewer.Backend.show中获取对组件“square”的引用Scala.js 如何在scalsjs react中获取组件的引用?,scala.js,scalajs-react,Scala.js,Scalajs React,这个医生 有点不清楚 我创建了一个小示例:“squareViewer”通过单击显示“square” 如何在方法squareViewer.Backend.show中获取对组件“square”的引用 import japgolly.scalajs.react._ import japgolly.scalajs.react.vdom.prefix_<^._ object squareViewer { class Backend($: BackendScope[Unit, Unit]) {
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
object squareViewer {
class Backend($: BackendScope[Unit, Unit]) {
def show() = Callback {
//???
//val r = ref to square instance
//r.backend.show()
}
def render() = {
<.div(
<.button("Show square", ^.onClick-->show()),
square.component.withRef("id1")()
)
}
}
val component = ReactComponentB[Unit]("squareViewer")
.renderBackend[Backend]
.buildU
}
object square {
case class State(visible: Boolean)
class Backend($: BackendScope[Unit, State]) {
def show() = $.setState(State(true))
def hide() = $.setState(State(false))
def render(s: State) = {
<.div("Yo!",
^.width:="100px", ^.height:="100px",
^.position:="absolute", ^.top:=0, ^.left:=0,
^.fontSize:="300%",
^.backgroundColor:="red",
!s.visible ?= ^.display.none,
^.onClick-->hide()
)
}
}
val component = ReactComponentB[Unit]("square")
.initialState(State(false))
.renderBackend[Backend]
.buildU
}
导入japgolly.scalajs.react_
导入japgolly.scalajs.react.vdom.prefix\up>这应该可以做到:
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
object squareViewer {
val squareRef = Ref.to(square.component, "square")
class Backend($: BackendScope[Unit, Unit]) {
def show() =
squareRef($).map(_.backend.show()).getOrElse(Callback.empty)
def render() = {
<.div(
<.button("Show square", ^.onClick-->show()),
square.component.withRef(squareRef)()
)
}
}
val component = ReactComponentB[Unit]("squareViewer")
.renderBackend[Backend]
.buildU
}
object square {
case class State(visible: Boolean)
class Backend($: BackendScope[Unit, State]) {
def show() = $.setState(State(true))
def hide() = $.setState(State(false))
def render(s: State) = {
<.div("Yo!",
^.style:="width:100px;height:100px;position:absolute;top:0;left:0;font-size:300%;background-color:red;",
!s.visible ?= ^.display.none,
^.onClick-->hide()
)
}
}
val component = ReactComponentB[Unit]("square")
.initialState(State(false))
.renderBackend[Backend]
.buildU
}
导入japgolly.scalajs.react_
导入japgolly.scalajs.react.vdom.prefix_