React Native 和 TypeScript:“RefObject<TextInput>”类型上不存在属性“focus”

问题描述 投票:0回答:2

这就是我正在做的事情:

  declare passCodeInput:  React.RefObject<TextInput>;

但是我在尝试调用

focus
方法时遇到了一个问题:

setTimeout(() => this.passCodeInput.focus());

enter image description here

我在

focus
上拨打
current
,例如
this.passCodeInput.current!.focus())
,但这对我来说不起作用。

javascript reactjs typescript react-native
2个回答
0
投票
import { NativeMethods, TextInputProps } from "react-native"

const inputRef = React.useRef<TextInputProps & NativeMethods>(null);

// later on in jsx

return (
  <TextInput
     ref={inputRef}
     style={styles.input}
     onChangeText={onChangeText}
     value={text}
  />
)

-1
投票

您可以像下面这样使用 ref :

import React, { useRef } from 'react'
...


const MyFormComponent = () => {

  const ref_input2 = useRef();
  const ref_input3 = useRef();

  return (
    <>
      <TextInput
        placeholder="Input1"
        autoFocus={true}
        returnKeyType="next"
        onSubmitEditing={() => ref_input2.current.focus()}
      />
      <TextInput
        placeholder="Input2"
        returnKeyType="next"
        onSubmitEditing={() => ref_input3.current.focus()}
        ref={ref_input2}
      />
      <TextInput
        placeholder="Input3"
        ref={ref_input3}
      />
    </>
  )
}

希望对您有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.