You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ShinyMCE在shinyDashboard的renderUI中无法正常工作求解决方案

问题:shinyMCE在renderUI中无法正常加载的解决办法

以下代码可正常运行,能正确渲染出tinyMCE富文本编辑器:

library(shiny)
library(shinydashboard)
library(shinyMCE)

ui <- dashboardPage(
  header = dashboardHeader(),
  sidebar = dashboardSidebar(),
  body = dashboardBody(
    # uiOutput("body")
    tinyMCE("tinyInput", "Some html text")
  )
)

server <- function(input, output, session) {
  # output$body <- renderUI({tinyMCE('tinyInput',"Some html text")})
}

shinyApp(ui = ui, server = server)

但将tinyMCE放入renderUI动态生成UI时,编辑器无法正常加载,仅显示纯文本输入框:

library(shiny)
library(shinydashboard)
library(shinyMCE)

ui <- dashboardPage(
  header = dashboardHeader(),
  sidebar = dashboardSidebar(),
  body = dashboardBody(
    uiOutput("body")
    # tinyMCE("tinyInput","Some html text")
  )
)

server <- function(input, output, session) {
  output$body <- renderUI({tinyMCE('tinyInput',"Some html text")})
}

shinyApp(ui = ui, server = server)

解决建议

问题根源是:页面初始加载时tinyMCE的初始化脚本已执行,而renderUI动态插入的元素不会自动触发初始化。需要手动为动态生成的编辑器触发初始化逻辑,以下是两种可行方案:

方案1:在renderUI中添加初始化脚本

直接在动态生成的UI后追加tinyMCE初始化的JS代码:

library(shiny)
library(shinydashboard)
library(shinyMCE)

ui <- dashboardPage(
  header = dashboardHeader(),
  sidebar = dashboardSidebar(),
  body = dashboardBody(
    uiOutput("body")
  )
)

server <- function(input, output, session) {
  output$body <- renderUI({
    tagList(
      tinyMCE("tinyInput", "Some html text"),
      tags$script(HTML("tinymce.init({selector: '#tinyInput'});"))
    )
  })
}

shinyApp(ui = ui, server = server)

方案2:使用htmlwidgets的onRender绑定初始化

借助htmlwidgets::onRender,在元素渲染完成后执行初始化:

library(shiny)
library(shinydashboard)
library(shinyMCE)
library(htmlwidgets)

ui <- dashboardPage(
  header = dashboardHeader(),
  sidebar = dashboardSidebar(),
  body = dashboardBody(
    uiOutput("body")
  )
)

server <- function(input, output, session) {
  output$body <- renderUI({
    mce_editor <- tinyMCE("tinyInput", "Some html text")
    onRender(mce_editor, function(el, x) {
      tinymce.init({selector: paste0("#", el$id)})
    })
  })
}

shinyApp(ui = ui, server = server)

内容的提问来源于stack exchange,提问作者Lev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 03:20:18