在 Select 下拉值后,我试图聚焦TextInput时出错.

这是我用来设置inputRef的函数

  let inputRef = useRef<TextInput | null>(null)

  const onSelectFormat = (format) => {
    setDropdownListVisibility('')
    setInputFocused(true)
    inputRef.current &&  inputRef.current.focus()
  }

发送inputRef变量的CustomInput组件

      <CustomInput
        value={value}
        onChangeText={onChangeInputText}
        isFocused={isInputFocused}
        onFocus={() => setInputFocused(true)}
        getRef={ref => (inputRef = { current: ref })}
      />

最后,这是我传递ref的子组件.

        <TextInput
          ref={getRef}
          value={value}
          onChangeText={onChangeText}
          style={styles.input}
          onFocus={onFocus}
        />

推荐答案

您的代码似乎部分设置为call-back refs,部分设置为常规引用(使用useRefcreateRef创建).

如果您将CustomInput元素中的getRef={ref => (inputRef = { current: ref })}替换为getRef={inputRef},代码应该可以工作,但如果您也使用props 名称inputRef而不是getRef,代码会更干净:

..
const inputRef = useRef<TextInput | null>(null)

const onSelectFormat = (format) => {
  setDropdownListVisibility('')
  setInputFocused(true)
  inputRef.current?.focus()
}
..
  ..
  <CustomInput
    value={value}
    onChangeText={onChangeInputText}
    isFocused={isInputFocused}
    onFocus={() => setInputFocused(true)}
    inputRef={inputRef}
  />
  ..
  ..
  <TextInput
    ref={inputRef}
    value={value}
    onChangeText={onChangeText}
    style={styles.input}
    onFocus={onFocus}
  />
  ..

(CustomInput的功能定义也适用于新的inputRefprops 名称)

Typescript相关问答推荐

为什么在TypScript中将类型守护的返回类型写成This is(

错误:note_modules/@types/note/globals.d.ts:72:13 -错误TS 2403:后续变量声明必须具有相同的类型

在TypScript手册中可以视为接口类型是什么意思?

React Hook中基于动态收件箱定义和断言回报类型

当类型断言函数返回假时,TypScript正在推断从不类型

参数类型undefined不能分配给参数类型字符串|未定义

防止获取发出不需要的请求

在键和值为ARGS的泛型函数中未正确推断类型

如何在编译时为不带常量的参数引发错误

对未到达受保护路由的路由环境做出react

是否可以判断某个类型是否已合并为内部类型?

复选框Angular 在Ngfor中的其他块中重复

具有匹配功能的TS通用事件处理程序

如何在具有嵌套数组的接口中允许新属性

两个名称不同的相同打字界面-如何使其干燥/避免重复?

TypeScript中的这些条件类型映射方法之间有什么区别?

如何为对象数组中的每个条目推断不同的泛型

如何在TypeScript中将元组与泛型一起使用?

在对象数组中设置值

如何在 TypeScript 类型定义中简化定义长联合类型