首页 > 解决方案 > 通过 js 在 R 中设置默认 textInput 值(作为 js 函数的结果)

问题描述

我想将 R 闪亮的应用程序与一个社交网络的 js SDK 一起使用。我想从 js API 获取用户 ID 并将其设置为 textInput 表单的默认值。但只有一次,第一次。

我设法使用Shiny.onInputChange()功能(或Shiny.setInputValue()闪亮> 1.1)实现的最佳结果

玩具示例:

ui <- fluidPage(

 textInput("uid",label = h4("Input ID"),value = "1"),
 actionButton("goButton", "Check this out!", class="btn-primary"),

 # getting user id via js
 tags$script(HTML(
  '
  uid = some_js_code;
  console.log("My uid - " + uid);

  // setting new value for input$uid variable
  Shiny.onInputChange("uid", uid);
  // for newer version of shiny 
  //Shiny.setInputValue("uid", uid);
  '
)

server <- function(input, output, session) {

  user<-reactive({

  input$goButton    
  user <- some_function_for_uid(input$uid)

  })

}

问题:

  1. 在第一次加载应用程序时变量“uid”的值没有改变。value="1"该值与 textInput 函数 ( )中的值保持一致

  2. 只有当我按下 goButton 时,服务器函数才会some_function_for_uid()接收变量的新值。但是文本形式的值仍然保持不变。

如何正确更改 textInput 中的默认值并避免描述的问题?先感谢您。

标签: javascriptrshiny

解决方案


要更新 中的值textInput

$("#uid").val(uid);

我不知道你想用这个按钮做什么。像这样可以吗:

ui <- fluidPage(

  textInput("uid", label = h4("Input ID"), value = "1"),
  verbatimTextOutput("showUID"),
  #actionButton("goButton", "Check this out!", class="btn-primary"),

  tags$script(HTML(
    '
    uid = "hello";

    // setting new value in the textInput
    $("#uid").val(uid);

    // setting new value for input$uid variable
    Shiny.onInputChange("uid", uid);
    '
  ))

)

server <- function(input, output, session) {

  user <- eventReactive(input$uid, {
    rep(input$uid, 3)
  })

  output[["showUID"]] <- renderText({user()})

}

推荐阅读