Dreamland.js问题:状态值变更时页面文本未更新
问题解决:Dreamland.js中state更新后preview区域未同步
问题根源
你定义的Editor和MainApp是普通函数,Dreamland.js无法自动追踪这类函数对$state的依赖,因此当state.currentText变化时,组件不会触发重渲染,导致preview区域文本无法更新。
解决方案
必须使用$component来创建响应式组件,让Dreamland能够追踪组件内部的state依赖,在state变化时自动重渲染组件。
修改后的完整代码
import "dreamland/dev"; let state = $state({ currentText: "" }) // 用$component包装Editor组件,使其成为响应式组件 const Editor = $component(() => { return ( <div id="editor"> <textarea value={state.currentText} on:input={(e: InputEvent) => { state.currentText = e.target!.value console.log(state.currentText) }} autofocus /> <div id="preview"> {state.currentText} </div> </div> ) }) // 同样用$component包装MainApp组件 const MainApp = $component(() => { return ( <div id="app"> <Editor /> </div> ) }) window.addEventListener('load', () => { document.body.appendChild(<MainApp />) })
关键说明
$component是Dreamland.js中创建响应式组件的核心API,它会自动收集组件内部对$state的依赖。- 当
state.currentText被更新时,被$component包裹的Editor组件会感知到依赖变化,触发重新渲染,preview区域的文本就会同步显示最新的内容。
内容的提问来源于stack exchange,提问作者CoolElectronics
相关产品推荐
相关产品推荐

