【发布时间】: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< FormInputPassword>(null);或任何合适的类型 -
@Nishant 给了我
Property 'focus' does not exist on type 'never'.ts(2339) -
能否包含
FormInputPassword的定义?我的猜测是您没有将它收到的ref转发到 DOM 节点 -
@Dancrumb 我已将其添加到问题中
标签: reactjs typescript ref use-ref