如何将字符串转换为小写? .toLowerCase() 无法正常工作

How to convert string to lowercase? .toLowerCase() not working properly

我想创建一个输入字段,returns 以小写字母输入文本。我正在使用博览会

const [login, setLogin] = useState('');
//...
<TextInput style={{backgroundColor:'#bbb'}}
   value={login}
   onChangeText={(val)=>setLogin(val.toLowerCase())}
   placeholder="email or username"
></TextInput>

我在我的设备上测试时得到了一个奇怪的结果。

我的输入:'K' => 登录 = 'k'

我的输入:'k' => 登录 = 'kkk'

我的输入:'k' => 登录 = 'kkkkkkk'

您可能需要尝试几次才能重新创建我的结果,因为这种情况并非每次都会发生。当我删除 .toLowerCase() 时,它工作正常。

我做了runnable example给你测试。 运行 它在网络模式下工作正常,但是当我 运行 在我的设备上时,出现了与我的项目中相同的错误。

这是 video 我在 运行 上 android 10 时发生的事情。你可以看到它并不总是发生,但有时它注册为如果我只按了两次“q”却按了三次

我认为您 运行 遇到了一个已知的 react-native 错误,与 Android 平台上的文本输入和大写有关。打开 github 问题 #27449.

作为解决方法,您可以强制文本输入在 Android 上使用 visible-password 键盘类型。

Working example供你测试:

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

export default function App() {
  const [login, setLogin] = useState('');
  return (
    <View style={styles.container}>
      <TextInput style={{backgroundColor:'#bbb'}}
        value={login}
        onChangeText={(val)=>setLogin(val.toLowerCase())}
        keyboardType={Platform.OS === 'ios' ? 'default' : 'visible-password'}
        placeholder="email or username"
      ></TextInput>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 80,
  },
});

解决方法归功于 simon-davies-avtura