我编写了一个相当简单的模块,由客户端上的 textInput 和更新该 textInput 值的服务器函数组成。为了实现这一点,我在服务器函数中调用 updateTextInput()。但是,客户端上的 textInput 不会更新。
我应该怎么做才能让我的模块服务器功能更新客户端上的 textInput?
这是我的代码的简化版本:
具有模块定义的 global.R
# Client side.
specifyInput <- function(id, points){
ns <- NS(id)
tagList(textInput(ns('points'), label='Total', value=points))
}
# Server side.
specify <- function(input, output, session){
ns <- session$ns
observe({
new.value = 2 * as.numeric(input$points)
#this line does not seem to work
updateTextInput(session, ns('points'), value = new.value)
})
# create dataframe with entered value
df <- reactive(data.frame(points = as.numeric(input$points)))
# return the dataframe
return(df())
}
Run Code Online (Sandbox Code Playgroud)
ui.R
specifyInput("ttlEntry", 10)
Run Code Online (Sandbox Code Playgroud)
服务器R
function(input, output, session){
test <- reactive(callModule(specify, "ttlEntry"))
#somewhere in the code, call test()
}
Run Code Online (Sandbox Code Playgroud)
实际上,当用户输入句点时,我想在输入的值后面附加一个 .5,例如,如果用户输入“10”。然后 textInput 更新为显示“10.5”但是出于测试目的,我已将该代码更改为 new.value = 2 * ...
任何帮助是极大的赞赏。
有几点需要注意,全部连接到模块服务器组件:
ns <- session$ns- 我认为这是为在模块中使用 renderUI 而保留的(请参阅这篇文章)。ns()模块服务器中 - 因此 ns('points')应该更改为'points'.df(),而应该只返回df不带括号的内容。进行这些更改后,应用程序即可运行,但请注意,会创建一个反馈循环,因此输入的值会不断加倍。您需要进一步修改您的代码逻辑,以便将输入的内容加倍(或按照您的描述添加 .5),然后将其保留。
下面发布了一个有效的单文件应用程序版本:
# Client side.
specifyInput <- function(id, points){
ns <- NS(id)
textInput(ns('points'), label = 'Total', value = points)
}
# Server side.
specify <- function(input, output, session, ...){
observe({
new.value = 2 * as.numeric(input$points)
updateTextInput(session, 'points', value = new.value)
})
# create dataframe with entered value
df <- reactive(data.frame(points = as.numeric(input$points)))
# return the dataframe
return(df)
}
# ui
ui <- specifyInput("ttlEntry", 10)
# server
server <- function(input, output, session){
test <- callModule(specify, "ttlEntry")
}
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)