React JS字符限制 [英] React js character limitation

查看:43
本文介绍了React JS字符限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在react js中实现textArea的宪章限制这是我的代码.

Im trying to implement a chartercter limit for a textArea in react js here is my code.

state = {
  chars_left: 140;
}

handleWordCount = event => {
  const charCount = event.target.value.length;
  const maxChar = this.state.chars_left;
  const charLength = maxChar - charCount;
  this.setState({ chars_left: charLength });
}

<textArea
  rows={6}
  type="text"
  maxLength="140"
  required
  onChange={this.handleWordCount}
/>

{ $ {this.state.chars_left} }

我有一个函数应该显示用户正在键入多少个字符,它从140开始,但是每次我键入单个字符时,每次键入130之类的字符都会跳过吨数

I have a function that should that show how many character the user is typing and it starts at 140 but it skips tons numbers every time i type something like 130 when i type a single character

问题可能是什么?

推荐答案

问题是您一直在根据旧值更新chars_left属性

the problem is you are keep updating the chars_left attribute based on the old value

关注将按预期进行

state = {
   chars_left: 140;
}

handleWordCount = event => {
    const charCount = event.target.value.length;
    const charLeft = 140 - charCount;
    this.setState({ chars_left: charLeft});
}

可以通过动态获取maxlengt attr来改进我的示例代码

My example code can be improved by dynamically getting the maxlengt attr

这篇关于React JS字符限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆