3 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
聽(tīng)起來(lái)您正在尋找的是ImperativeHandle掛鉤。
來(lái)自 React 文檔:
useImperativeHandle 自定義使用 ref 時(shí)暴露給父組件的實(shí)例值
下面的代碼應(yīng)該適合你:
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貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊
好吧,你可以這樣做:
<input ref={myRef} value={myRef.current.value} />
唯一的問(wèn)題是 refs DO NOT update or reredender the component, so, the value will never update... 而不是它可能會(huì)在您嘗試將不受控制的輸入作為受控輸入時(shí)拋出錯(cuò)誤

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