簡體   English   中英

如何將 TextInput 集中在 React Native 中的按鈕按下上

[英]How to focus TextInput on button press in React Native

我有一個 TextInput 組件,它只能在組件安裝時進行編輯。 當按下按鈕時,它應該變得可編輯和自動聚焦。 正如我正確理解的那樣, autoFocus屬性僅適用於第一次安裝。 有沒有辦法在 state 更改上實現這一點?

import { FunctionComponent } from 'react';
import { View, TextInput, TextInputProps } from 'react-native';


interface InputTextBoxProps {
  editingState: boolean;
}

type InputProps = TextInputProps & InputTextBoxProps;

const InputTextBox: FunctionComponent<InputProps> = ({editingState, ...props}) => {
  return (
    <View>
      <TextInput
        {...props}
        multiline={true} 
        style={styles.textStyle}
        editable={editingState}
        autoFocus={editingState}
      >
      </TextInput>
    </View>
  );
};
const refInput = React.useRef(null);
 ...
<TextInput
  {...props}
  ref={refInput}
  multiline={true} 
  style={styles.textStyle}
  editable={editingState}>
</TextInput>

在按鈕上單擊 function

refInput.current.focus()

更新

這是可行的解決方案,好像editable道具似乎僅適用於組件安裝,因此不會通過 state 更改。 該解決方案基於mainak的答案。

import { FunctionComponent, useRef } from 'react';
import { View, StyleSheet, TextInput, TextInputProps } from 'react-native';

interface InputTextBoxProps {
  editingState: boolean;
}

type InputProps = TextInputProps & InputTextBoxProps;

const InputTextBox: FunctionComponent<InputProps> = ({editingState, ...props}) => {

  const refInput = useRef<TextInput>(null);

  if (editingState) {
    refInput.current?.focus();
  } else {
    refInput.current?.blur();
  }

  return (
    <View pointerEvents={editingState ? 'auto' : 'none'}>
      <TextInput
        {...props}
        ref={refInput}
        multiline={true}
      >
      </TextInput>
    </View>
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM