亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 useRef 更改輸入值

使用 useRef 更改輸入值

慕桂英546537 2023-05-11 14:23:46
我用 React 的 useRef 鉤子捕獲了一個元素。如果我使用 console.log(this.inputRef) 我得到:<input aria-invalid="false" autocomplete="off" class="MuiInputBase-input-409 MuiInput-input-394" placeholder="Type ItemCode or scan barcode" type="text" value="2">有沒有辦法使用 this.inputRef 更改該元素的值?然后強制重新渲染?
查看完整描述

3 回答

?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

聽起來您正在尋找的是ImperativeHandle掛鉤。

來自 React 文檔:

useImperativeHandle 自定義使用 ref 時暴露給父組件的實例值

下面的代碼應該適合你:

function ValueInput(props, ref) {

? const inputRef = useRef();

? useImperativeHandle(ref, () => ({

? ? changeValue: (newValue) => {

? ? ? inputRef.current.value = newValue;

? ? }

? }));

? return <input ref={inputRef} aria-invalid="false" autocomplete="off" class="MuiInputBase-input-409 MuiInput-input-394" placeholder="Type ItemCode or scan barcode" type="text" value="2">

}

ValueInput = forwardRef(ValueInput);

查看完整回答
反對 回復 2023-05-11
?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

好吧,你可以這樣做:

<input ref={myRef} value={myRef.current.value} />

唯一的問題是 refs DO NOT update or reredender the component, so, the value will never update... 而不是它可能會在您嘗試將不受控制的輸入作為受控輸入時拋出錯誤


查看完整回答
反對 回復 2023-05-11
?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

也許這可以幫助


return(

    <input type="text" ref={inptRef}  />

    <button onClick={()=>inptRef.current.value = ""}>clear input</button>


)


查看完整回答
反對 回復 2023-05-11
  • 3 回答
  • 0 關注
  • 292 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號