简体   繁体   English

在 React Native 功能组件中未定义 useRef.current

[英]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.

相关问题 useRef.current 存在,但是是 null 取决于 scope - useRef.current exists, but is null depending on scope React - useRef 与 TypeScript 和功能组件 - React - useRef with TypeScript and functional component 使用反应挂钩 (useRef) 将 class 组件转换为功能组件—如何避免“未定义”错误 - Converting class component to functional component using react hooks (useRef)—how to avoid “undefined” error 在功能组件中反应原生 typeScript 和 forwardRef - React native typeScript and forwardRef in a functional component 将下一个文本输入集中在功能组件中的本机反应中 - focus next textInput in react native in functional component 测试依赖于 Promise 的 React Native 功能组件 - Testing React Native Functional Component With Dependency on Promise React TypeScript:功能组件中 UseRef 的替代方案 - React TypeScript: Alternatives to UseRef in functional components 如何从存储更新 React Native 功能组件状态 - How to Update React Native Functional Component State from Storage 无法在 React Native 项目(功能组件)中重新渲染视图 - Unable to re-render view in React Native project (functional component) 如何在反应原生的功能组件中过滤 state 阵列 - How can i filter an state array in functional component in react native
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM