簡體   English   中英

如何通過 onClick 按鈕將輸入引用轉發給函數

[英]How to forward input ref to a function by onClick button

我正在嘗試通過單擊按鈕將輸入參考文本/字符串數據轉發給函數。 但我無法使用按鈕將數據轉發或傳遞給我的函數

--questionRef 是我的參考輸入數據

--answerQuestion 是我的功能

<input ref={questionRef} size="80"></input>
 <button type="button" onClick={answerQuestion} >Enter</button>

我嘗試使用我的按鈕將 questionRef 輸入轉發到 answerQuestion 函數,但它失敗了。 當我點擊鍵盤上的回車時它也有效

很簡單:

<input ref={questionRef} size="80"></input>
   <button 
        type="button" 
        onClick={() => answerQuestion(questionRef)}
   >Enter
   </button>

最終,您還可以將onClick事件包含到您的函數中,具體取決於您需要對其執行的操作:

<input ref={questionRef} size="80"></input>
   <button 
        type="button" 
        onClick={(e) => answerQuestion(questionRef, e)}
   >
     Enter
   </button>

基於 Junius L. 評論:

const questionRef = useRef()
const answerQuestion = () => {
      doSomethingWithRef(questionRef) // questionRef is accessible in whole component scope
}

<input ref={questionRef} size="80"></input>
   <button 
        type="button" 
        onClick={answerQuestion}
   >Enter
   </button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM