首页 > 解决方案 > React Native 设置 TextInput 值大写

问题描述

我是 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} />
    ...
  }
}

标签: javascriptreact-native

解决方案


如果要将输入字符串更改为大写字符串,则可以在 TextInput 中使用autoCapitalize道具。

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

道具autoCapitalize有以下选项:

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

默认值为句子


推荐阅读