简体   繁体   English

通过js在R Shiny中设置默认的textInput值(作为js函数的结果)

[英]Setting default textInput value in R shiny via js (as result of js function)

I want to use R shiny app with js SDK of one social network. 我想将R Shiny应用程序与一个社交网络的js SDK一起使用。 I want to get user id from js API and set it as default value for textInput form. 我想从js API获取用户ID,并将其设置为textInput表单的默认值。 But only once, for the first time. 但是只有一次,这是第一次。

The best result I managed to achieve using Shiny.onInputChange() function (or Shiny.setInputValue() for shiny>1.1) 我设法使用Shiny.onInputChange()函数(或Shiny.setInputValue()表示Shiny.setInputValue() > 1.1)获得了最好的结果

Toy example: 玩具示例:

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)

  })

}

Problems: 问题:

  1. On first load of app value of variable "uid" is not changing. 首次加载应用程序时,变量“ uid”的值不变。 The value remains as it was in textInput function ( value="1" ) 该值保留为textInput函数中的value="1"value="1"

  2. Server function some_function_for_uid() receive new value of variable only when I press goButton. 服务器功能some_function_for_uid() 在按goButton 时才接收变量的新值。 But value in text form still remains the same. 但是,文本形式的值仍然保持不变。

How correctly change default value in textInput and avoid described problems? 如何正确更改textInput中的默认值并避免描述的问题? Thank you in advance. 先感谢您。

To update the value in the textInput : 要更新textInput的值:

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

I don't know what you want to do with the button. 我不知道您想使用该按钮做什么。 Is it OK like this: 这样可以吗:

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()})

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM