如何在React Native中为useRef挂钩设置Typescript类型?

时间:2019-12-16 04:21:59

标签: reactjs typescript react-native

如何为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}
    />
  )

}

1 个答案:

答案 0 :(得分:1)

应该是

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