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>
)
添加回答
举报