【问题标题】:How do you set the Typescript type for useRef hook in React Native?如何在 React Native 中为 useRef 钩子设置 Typescript 类型?
【发布时间】:2025-12-13 07:55:02
【问题描述】:

如何正确键入 React Native TextInput 的 useRef?
使用下面的代码,我得到以下错误。

Property 'isFocused' does not exist on type 'MutableRefObject<TextInput>'

import React, { useRef } from 'react';
import { TextInput } from 'react-native';

const TestScreen = () => {

  const searchInputRef = useRef<TextInput>();

  const updateSearchText = (searchText: string) => {
    console.log(searchTextRef.isFocused()); //  ???? Error here.
  };

  return (
    <TextInput
      ref={searchInputRef}
      placeholder="Search"
      onChangeText={(text: string) => updateSearchText(text)}
      autoCorrect={false}
      autoCapitalize="none"
      value={searchText}
    />
  )

}

【问题讨论】:

    标签: reactjs typescript react-native


    【解决方案1】:

    应该是

     const updateSearchText = (searchText: string) => {
        console.log(searchInputRef.current.isFocused());
      };
    
    

    【讨论】:

    • 嗯...这有点尴尬。 ? 谢谢!