react-native中的TextInput长度计数器

You*_*ang 2 react-native

我的场景中有一个 maxLength 为 100 的 TextInput,我想在下面添加一个计数器,显示类似“38/100”的内容,使用“onChangeText”自动更新。

所以我必须弄清楚输入值的长度,以某种方式将它存储在 this.state.textLength 中,同时将值本身存储到 this.state.text,但我不知道如何在“onChangeText = {(文本) => ...}" 函数。

这是我的简化代码:

export class RequestScene extends Component {
  constructor() {
    super();

    this.state={
      text: '',
      textLength: 0,
      category: '',
      time: ''
    };
  }

  render(){

    return(
      <View style={{
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center'
      }}>
        <View style={{
            height: 200
        }}>
            <TextInput style={{
                height: 200,
                width: 360,
                borderColor: 'lightgray',
                borderWidth: 1,
                padding: 3,
                borderRadius: 3,
                fontSize: 24}}
                maxLength={100}
                placeholder='?? ???? ???? ????'
                multiline={true}

                // this is where I am stuck. What should I do with 'textLength'?
                onChangeText={
                    (text)=>this.setState({text})
                    (text)=>this.setState({textLength})
                }
            />
            <Text style={{
                fontSize:10,
                color:'lightgrey',
                textAlign: 'right'
            }}> 
                // currently this counter only shows '0/100'
                {this.state.textLength}/100 
            </Text>
Run Code Online (Sandbox Code Playgroud)

nma*_*mac 5

onChangeText()函数返回一个字符串。您可以执行以下操作:

const maxLength = 100;
this.setState({
  textLength: maxLength - text.length,
  text, // same as `text: text`
});
Run Code Online (Sandbox Code Playgroud)