gpt4 book ai didi

reactjs - Ref 对象可能是未定义的 TypeScript React

转载 作者:行者123 更新时间:2023-12-03 13:31:41 25 4
gpt4 key购买 nike

我有一个使用钩子(Hook)将输入值设置为组件状态的组件。当输入值的长度超过 0 个字符时,我想添加一个类,但是我遇到了 TypeScript 说我的 ref 可能未定义的问题。

即使我检查 ref 是否存在于包装代码以添加类的条件中,我也无法摆脱这个错误。我不确定这个问题的解决方案。

错误: Object is possibly 'undefined'inputValue.current.classList.add(inputHasContentClassName);

import React, { useState, useEffect, useRef } from 'react';

const Component: React.FC = () => {
const [inputValue, setInputValue] = useState('');
const myRef = useRef();

useEffect(() => {
const inputHasContentClassName = 'input--has-value';

if (inputValue.length > 0 && inputValue) {
inputValue.current.classList.add(inputHasContentClassName);
} else {
inputValue.current.classList.remove(inputHasContentClassName);
}
}, [inputValue]);

function handleInputChange(e: React.FormEvent<HTMLInputElement>) {
setInputValue(e.currentTarget.value);
}

function handleSubmit(e: React.FormEvent) {
e.preventDefault();

console.log('Submit form');
}

return (
<>
<section>
<form onSubmit={handleSubmit}>
<div>
<input
ref={myRef}
onChange={handleInputChange}
type="number"
/>
<label>Input Label</label>
</div>
<button
type="submit"
disabled={inputValue.length === 0}
>
Submit
</button>
</form>
</section>
</>
);
};

export default Component;

最佳答案

useRef()返回一个带有 current 的对象属性,它包含你真正关心的对象。在第一次渲染完成之前,current属性将为空。这意味着该 ref 的类型是:

{ current: WhateverTypeYouCareAbout | null }
这意味着你必须处理 null作为 current 的可能值属性(property)。但是ref对象本身会一直存在,只是它的 current属性可能是 null .
我会简单地存储 current您的 ref 在变量中的值,测试该存在,然后使用它。
  useEffect(() => {
const inputHasContentClassName = 'input--has-value';
const inputElement = inputValue.current;

if (inputElement && inputElement.value.length > 0) {
inputElement.classList.add(inputHasContentClassName);
} else {
inputElement.classList.remove(inputHasContentClassName);
}
}, [inputValue]);
您还可以通过执行以下操作告诉 TypeScript 编译器您的 ref 的类型(在本例中为 HTMLInputElement):
const myRef = useRef<HTMLInputElement>();

关于reactjs - Ref 对象可能是未定义的 TypeScript React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59901775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com