你可以在 React Native 的 TextInput 中实现一个清除按钮,而不会失去焦点。

huangapple go评论76阅读模式
英文:

How can I implement a clear button in a React Native TextInput that doesn't lose focus?

问题

以下是您要翻译的内容:

"Trying to implement a TextInput clear button in react native loses focus to the text input without invoking the function in the first place

I have a Task to implement A text input that has a little clear button which sets the input field to "". it looks like this:
input example

I implemented it as needed however when I click the X icon , responsible for clearing the input text while maintaining focus to allow the user to continue editing what happens is that It registers as a click outside the input field and it triggers on blur therefore not executing the clear function at all. here is my code:

import {
  View,
  TextInput,
  Pressable,
  Image,
  GestureResponderEvent,
  Text,
  ScrollView,
} from 'react-native';
import React, {Dispatch, SetStateAction, useRef, useState} from 'react';
import styles from './InputField.styles';
import {useTheme} from 'react-native-paper';
import assets from '@common/assets';
import {layouts} from '@common/constants';
type Props = {
  title?: string;
  icon?: string;
  placeholder?: string;
  isInvalid?: boolean;
  caption?: string;
  value: string;
  valueSetter: Dispatch<SetStateAction<string>>;
  disabled?: boolean;
  autoFill?: boolean;
};
export default function InputField({
  title,
  icon,
  placeholder,
  isInvalid,
  value,
  valueSetter,
  caption,
  disabled = false,
  autoFill = false,
}: Props) {
  const theme = useTheme();
  const [focused, setFocused] = useState(false);
  const inputRef = useRef<TextInput>(null);

  return (
    <View>
      <Pressable
        // onPress={() => inputRef.current?.focus()}
        style={styles(theme).mainContainer}>
        <Text style={styles(theme, focused, disabled).title}>{title}</Text>
        <View style={styles(theme, focused, disabled, isInvalid).contentStyle}>
          {icon && (
            <Image
              style={styles(theme).imgContainer}
              resizeMethod="resize"
              source={assets.PersonImage}
            />
          )}
          <TextInput
            editable={!disabled}
            selectionColor={theme.neutralGray1}
            value={value}
            onChangeText={valueSetter}
            onFocus={() => setFocused(true)}
            onBlur={() => setFocused(false)}
            style={styles(theme, focused, disabled, isInvalid).inputField}
            placeholder={placeholder}
            ref={inputRef}
          />
          {focused && (
            <Pressable
              onPress={() => {
                valueSetter('');
              }}>
              <Image style={{...layouts.ms.lg}} source={assets.InputClear} />
            </Pressable>
          )}
        </View>
        {caption && (
          <Text
            style={
              isInvalid
                ? styles(theme, focused, disabled).invalidCaption
                : styles(theme, focused, disabled).caption
            }>
            {caption}
          </Text>
        )}
      </Pressable>
    </View>
  );
}

请注意,代码中的注释和一些特定的编程术语未进行翻译。如果您需要进一步的翻译或解释,请告诉我。

英文:

Trying to implement a TextInput clear button in react native loses focus to the text input without invoking the function in the first place

I have a Task to implement A text input that has a little clear button which sets the input field to "". it looks like this:
input example

I implemented it as needed however when I click the X icon , responsible for clearing the input text while maintaining focus to allow the user to continue editing what happens is that It registers as a click outside the input field and it triggers on blur therefore not executing the clear function at all. here is my code:

import {
View,
TextInput,
Pressable,
Image,
GestureResponderEvent,
Text,
ScrollView,
} from &#39;react-native&#39;;
import React, {Dispatch, SetStateAction, useRef, useState} from &#39;react&#39;;
import styles from &#39;./InputField.styles&#39;;
import {useTheme} from &#39;react-native-paper&#39;;
import assets from &#39;@common/assets&#39;;
import {layouts} from &#39;@common/constants&#39;;
type Props = {
title?: string;
icon?: string;
placeholder?: string;
isInvalid?: boolean;
caption?: string;
value: string;
valueSetter: Dispatch&lt;SetStateAction&lt;string&gt;&gt;;
disabled?: boolean;
autoFill?: boolean;
};
export default function InputField({
title,
icon,
placeholder,
isInvalid,
value,
valueSetter,
caption,
disabled = false,
autoFill = false,
}: Props) {
const theme = useTheme();
const [focused, setFocused] = useState(false);
const inputRef = useRef&lt;TextInput&gt;(null);
return (
&lt;View&gt;
&lt;Pressable
// onPress={() =&gt; inputRef.current?.focus()}
style={styles(theme).mainContainer}&gt;
&lt;Text style={styles(theme, focused, disabled).title}&gt;{title}&lt;/Text&gt;
&lt;View style={styles(theme, focused, disabled, isInvalid).contentStyle}&gt;
{icon &amp;&amp; (
&lt;Image
style={styles(theme).imgContainer}
resizeMethod=&quot;resize&quot;
source={assets.PersonImage}
/&gt;
)}
&lt;TextInput
editable={!disabled}
selectionColor={theme.neutralGray1}
value={value}
onChangeText={valueSetter}
onFocus={() =&gt; setFocused(true)}
onBlur={() =&gt; setFocused(false)}
style={styles(theme, focused, disabled, isInvalid).inputField}
placeholder={placeholder}
ref={inputRef}
/&gt;
{focused &amp;&amp; (
&lt;Pressable
onPress={() =&gt; {
valueSetter(&#39;&#39;);
}}&gt;
&lt;Image style={{...layouts.ms.lg}} source={assets.InputClear} /&gt;
&lt;/Pressable&gt;
)}
&lt;/View&gt;
{caption &amp;&amp; (
&lt;Text
style={
isInvalid
? styles(theme, focused, disabled).invalidCaption
: styles(theme, focused, disabled).caption
}&gt;
{caption}
&lt;/Text&gt;
)}
&lt;/Pressable&gt;
&lt;/View&gt;
);
}

答案1

得分: 0

我找到了问题,与上面的代码无关。我在另一个屏幕中在ScrollView内呈现了这个组件,所以我不得不在父级scrollview中添加keyboardShouldPersistTaps="handled"属性,这样它就不会失去子组件的焦点。

英文:

I found the issue and it has nothing to do with the code above. I render this component inside a ScrollView in another screen so I had to add the prop keyboardShouldPersistTaps=&quot;handled&quot; to the parent scrollview so that it doesnt lose the focus of the child component

huangapple
  • 本文由 发表于 2023年5月29日 15:36:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76355463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定