【问题标题】:useRef not working [TypeError: null is not an object (evaluating 'filed2.current.focus')]useRef 不工作 [TypeError: null 不是对象(评估'filed2.current.focus')]
【发布时间】:2021-05-08 20:51:42
【问题描述】:

每当按下键盘上的下一个按钮时,我都会尝试专注于下一个输入字段。

从 react native 文档中我了解到我们需要使用 useRef 钩子。但是按照文档

TypeError: null is not an object (evaluating 'filed2.current.focus')

我正在使用所有软件包的最新版本,以及带有 typescript 模板的新反应原生应用程序。

这是我目前掌握的一些代码:

import React, {useRef} from 'react';

...

  const filed1 = useRef(null);
  const filed2 = useRef(null);

  const onButtonClick = () => {
    filed2.current.focus();
  };

  return (
    <>
      <FormInputPassword
        ref={filed1}
        returnKeyType="next"
        onSubmitEditing={onButtonClick}
        blurOnSubmit={false}
      />
      <FormInputPassword
        ref={filed2}
        returnKeyType="done"
        blurOnSubmit={false}
      />
    </ >
  );

编辑:


function FormInputPassword(props) {
  return (
      <FormInputView>
        <Input {...props} />
      </FormInputView>
  );
}


FormInputPassword.defaultProps = {
  blurOnSubmit: true,
  autoCorrect: false,
  editable: true,
};

【问题讨论】:

  • 不应该是import React, {useRef} from 'react';吗?
  • filed2.current 可能为空。使用可选链接:filed2.current?.focus(); 此外,您需要使用参数化类型 const filed2 = useRef&lt; FormInputPassword&gt;(null); 或任何合适的类型
  • @Nishant 给了我Property 'focus' does not exist on type 'never'.ts(2339)
  • 能否包含FormInputPassword的定义?我的猜测是您没有将它收到的ref 转发到 DOM 节点
  • @Dancrumb 我已将其添加到问题中

标签: reactjs typescript ref use-ref


【解决方案1】:

函数组件不能有 ref 实例。

React.forwardRef((props,ref) => {
  return (
      <FormInputView ref={ref}>
        <Input {...props} />
      </FormInputView>
  );
});

【讨论】:

  • FormInputView 可能需要做同样的事情,(或者ref 应该直接在&lt;Input&gt; 上设置)
【解决方案2】:

如果FormInputPassword是一个函数组件,那么你需要用[forwardRef][1]包裹它。

函数式组件默认不接受 refs,所以你需要将其包装起来,然后将 ref 转发到组件内的 DOM 组件或类组件。

【讨论】:

    猜你喜欢
    • 2019-10-18
    • 2022-01-05
    • 2021-10-20
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多