React Native Set TextInput Value Uppercase(大写)

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

我是React Native的新手,不知道为什么会显示意外的结果。如果我输入'a',然后输入'a',它就会显示'AAA',以此类推。

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      userName: ''
    }
  }

  formatUserName = (textValue) => {
    // If I remove toUpperCase() below, it shows expected result.
    this.setState({ userName: textValue.toUpperCase() });
  }

  render() {
    ...
    <TextInput
      onChangeText={textValue => this.formatUserName(textValue)}
      value={this.state.userName} />
    ...
  }
}
javascript react-native
1个回答
1
投票

我也遇到了同样的问题。在iOS中,它可以完美地工作,但只有在android中才有问题。

这个小技巧似乎对我有用。

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      userName: ''
    }
  }

  formatUserName = (textValue) => {
    this.setState({ userName: textValue.toUpperCase() });
  }

  render() {
    ...
    <TextInput
      onChangeText={textValue => this.formatUserName(textValue)}
      keyboardType={Platform.OS === 'ios' ? 'default' : 'visible-password'}
      value={this.state.userName} />
    ...
  }
}

3
投票

如果你想把输入字符串改成大写字母,那么你可以使用 autoCapitalize TextInput中的道具。

<TextInput
  autoCapitalize = {"characters"}
  onChangeText={(text) => this.setState({ userName: text })}
  value={this.state.userName} />

道具 autoCapitalize 有以下选项。

  • 字符:所有字符。
  • words:每个单词的第一个字母。
  • sentences:每个句子的第一个字母(默认)。
  • none:不自动大写。

默认值是 句子

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