【问题标题】:Typescript React useRef object possibly null (Uncontrolled Component)Typescript React useRef 对象可能为空(不受控制的组件)
【发布时间】:2022-01-01 12:48:33
【问题描述】:

我正在尝试对输入元素使用 ref,然后使用 inputRef.current.value 获取其值 但我在inputRef.current 收到错误Object is possibly 'null'.ts(2531)

我尝试了几种不同的解决方案,但还没有成功。任何帮助表示赞赏。

interface RefObject<T> {
    readonly current: T | null
  }
  
const Uncontrolled: React.FC = () => {
    // const inputRef = useRef< HTMLInputElement | null> (null);
    const inputRef:RefObject<HTMLInputElement> = useRef< HTMLInputElement | null> (null);
    
    function alertValue() {
        alert(inputRef.current.value);         //Object is possibly 'null', under inputRef.current
    }

    return (
        <div>
            <p> Uncontrolled components do not have state data</p>
            <input type="text" ref={inputRef} />
            <button onClick={alertValue}>Click Me</button>
        </div>
    )
}

我的解决方案来自:

useRef TypeScript - not assignable to type LegacyRef<HTMLDivElement>

Object is possibly null in TypeScript React

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    虽然您可以使用可选链接或! 来断言.current 属性不是无效的...

    alert(inputRef.current!.value);
    

    更好的方法是使输入受控并记录状态。

    const [value, setValue] = useState('');
    function alertValue() {
        alert(value);
    }
    // ...
    <input value={value} onchange={e => { setValue(e.currentTarget.value); }} />
    

    【讨论】:

    • 谢谢!工作,我也会研究可选链接。对于这个组件,我试图让它不受控制,因此是组件名称。我会在 8 分钟内接受答复
    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 2019-11-10
    • 2020-06-18
    • 2022-01-08
    • 2019-10-22
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    相关资源
    最近更新 更多