我需要在我的UI的多个选项卡中重复使用用户在第一个选项卡中提供的输入.
似乎不可能在服务器中使用renderUI并在我的不同选项卡中使用uiOutput调用其输出.这是一个可重现的代码
ui <- pageWithSidebar(
headerPanel("Hello !"),
sidebarPanel(
tabsetPanel(
tabPanel("a",
textInput(inputId = "xyz", label = "abc", value = "abc")),
tabPanel("b", uiOutput("v.xyz"))
,tabPanel("b", uiOutput("v.xyz"))
)
),
mainPanel())
server <- function(input,output){
output$v.xyz <- renderUI({
input$xyz
})
}
runApp(list(ui=ui,server=server))
Run Code Online (Sandbox Code Playgroud)
还有另一种方法来实现这一目标吗?
非常感谢任何建议.
你不能(不应该)在HTML文档中有两个具有相同ID的元素(无论是否使用Shiny).当然,当使用具有相同ID的多个元素的Shiny时将会出现问题.我还会主观地投票通过使用有意义的变量名来大幅提高代码.
用这个输入你想要做什么也不是很清楚.您是否希望输入框显示在多个选项卡上?或者textInput的值要显示在多个选项卡上?
如果是前者,在我看来,没有明显的方法可以做到这一点,而不会违反"具有相同ID的多个元素"条款.后者会更容易(只需使用a renderText
并将其发送给a verbatimOutput
),但我不认为这就是你所要求的.
所以你真正想要的是同步的多个文本输入(具有不同的ID).您可以使用以下内容在服务器上的单独观察器中执行此操作:
ui <- pageWithSidebar(
headerPanel("Hello !"),
sidebarPanel(
tabsetPanel(
tabPanel("a",
textInput(inputId = "text1", label = "text1", value = "")),
tabPanel("b",
textInput(inputId = "text2", label = "text2", value = ""))
)
),
mainPanel()
)
INITIAL_VAL <- "Initial text"
server <- function(input,output, session){
# Track the current value of the textInputs. Otherwise, we'll pick up that
# the text inputs are initially empty and will start setting the other to be
# empty too, rather than setting the initial value we wanted.
cur_val <- ""
observe({
# This observer depends on text1 and updates text2 with any changes
if (cur_val != input$text1){
# Then we assume text2 hasn't yet been updated
updateTextInput(session, "text2", NULL, input$text1)
cur_val <<- input$text1
}
})
observe({
# This observer depends on text2 and updates text1 with any changes
if (cur_val != input$text2){
# Then we assume text2 hasn't yet been updated
updateTextInput(session, "text1", NULL, input$text2)
cur_val <<- input$text2
}
})
# Define the initial state of the text boxes
updateTextInput(session, "text1", NULL, INITIAL_VAL)
updateTextInput(session, "text2", NULL, INITIAL_VAL)
}
runApp(list(ui=ui,server=server))
Run Code Online (Sandbox Code Playgroud)
设置初始状态可能比cur_val
我跟踪更简洁.但是我想不出头顶的东西,所以就是这样.