admin管理员组

文章数量:1290754

I'm facing a problem with React Native TextInput.

I want to make a custom password input component because RN doesn't have good built-in tools and if I use the secureTextEntry attribute it just makes my text invisible, instead I want to mask all typed characters as asterisk symbols('*').

import React, {useState} from 'react';
import {View, TextInput, TouchableOpacity, Text} from 'react-native';

const MaskedPasswordInput = () => {
  const [isMasked, setIsMasked] = useState<boolean>(true);
  const [value, setValue] = useState<string>('');

  const handleTextChange = (text: string) => {
    setValue(text);
  };

  const handleTogglePasswordVisibility = () => {
    setIsMasked(prev => !prev);
  };

  return (
    <View>
      <TextInput
        placeholder={'Pasword'}
        value={isMasked ? '*'.repeat(value.length) : value}
        onChangeText={handleTextChange}
      />
      <TouchableOpacity
        activeOpacity={1}
        onPress={handleTogglePasswordVisibility}>
        <Text>Show/Hide Password</Text>
      </TouchableOpacity>
    </View>
  );
};

export default MaskedPasswordInput;

The problem here is that when I type once the input keeps getting duplicated when masked. Then I tried making some adjustment by only getting the last character when masked since I found the changing of value to asterisks makes an extra change triggering onChangeText and making another function call which makes the logic break and cause duplicating.

Please help me, I would really appreciate it! Thank you!

本文标签: user interfaceReact native39s text input duplicates input charactersStack Overflow