简体   繁体   中英

How do you set the Typescript type for useRef hook in React Native?

How do I correctly type the useRef for a React Native TextInput?
With the below code I get the following error.

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}
    />
  )

}

It should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM