[英]useRef.current is undefined in a React Native functional component
I'm trying to focus a text input field once the user clicks a button.用户单击按钮后,我正在尝试集中文本输入字段。 The code looks as follows:
代码如下所示:
const refName = React.useRef();
const changeFocus = () => {
refName.current.focus();
}
with the text input having an attribute ref
defined as refName
.文本输入的属性
ref
定义为refName
。 This gives me an error ( undefined is not an object (evaluating 'refName.current.focus')
), and when I rewrite the changeFocus
function as console.log(refName)
this is what I get:这给了我一个错误(
undefined is not an object (evaluating 'refName.current.focus')
),当我将changeFocus
function 重写为console.log(refName)
这就是我得到的:
Object {
"current": undefined,
}
I'm not sure how else I'm supposed to define the reference or how else to approach this problem.我不确定我应该如何定义参考或如何解决这个问题。 Thanks
谢谢
You initialize your ref without a value, so there will be a moment that ref.current
is undefined
before it gets the value of the component that you attach it to.您在没有值的情况下初始化 ref,因此在获得附加它的组件的值之前,会有一段时间
ref.current
undefined
。
You need to make your function call conditional so that it only happens if ref.current
has been set:您需要使您的 function 调用有条件,以便仅在设置了
ref.current
时才会发生:
const changeFocus = () => {
refName.current?.focus();
}
You also need to declare the expected type for the ref, since it cannot be inferred from an initial value.您还需要声明 ref 的预期类型,因为它不能从初始值推断出来。 The type could be the type of the specific component or it could be this:
类型可以是特定组件的类型,也可以是:
interface Focusable {
focus(): void;
}
const refName = React.useRef<Focusable>();
That should fix errors that you get when setting the ref
property on the component.这应该可以修复在组件上设置
ref
属性时遇到的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.