使用 useRef 更改输入值

Chr*_*cia 6 html javascript jquery reactjs material-ui

我使用 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">
Run Code Online (Sandbox Code Playgroud)

有没有办法使用 this.inputRef 更改该元素的值?然后强制重新渲染?

Bru*_*iro 6

听起来您正在寻找的是ImperativeHandle挂钩。

来自反应文档:

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);
Run Code Online (Sandbox Code Playgroud)

文档(更新): https: //react.dev/reference/react/useImperativeHandle