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);

TA貢獻1858條經驗 獲得超8個贊
好吧,你可以這樣做:
<input ref={myRef} value={myRef.current.value} />
唯一的問題是 refs DO NOT update or reredender the component, so, the value will never update... 而不是它可能會在您嘗試將不受控制的輸入作為受控輸入時拋出錯誤

TA貢獻1815條經驗 獲得超13個贊
也許這可以幫助
return(
<input type="text" ref={inptRef} />
<button onClick={()=>inptRef.current.value = ""}>clear input</button>
)
添加回答
舉報