[英]How to create a counter that calculates the remaining characters?
I'm trying to create a counter that calculates the remaining characters but I cannot. 我正在尝试创建一个计数器来计算剩余字符,但我不能。 I want to set the allowed characters to 100 and then subtract the number of characters written by the user from the 100, I wrote this
我想将允许的字符设置为100,然后从100中减去用户写的字符数,我这样写
class TextArea extends Component
{
state =
{
chars: 0,
}
charsRemaining()
{
var myTextArea = document.querySelector("textarea").value.length;
this.setState({chars: this.state.chars - myTextArea});
return myTextArea;
}
render()
{
return (
<div>
<textarea onKeyDown={this.charsRemaining()} cols="60" rows="10"></textarea>
<span>{this.state.chars}</span>
</div>
);
};
};
I thought if I set a variable to document.querySelector("textarea").value.length
that would work. 我以为如果将变量设置为
document.querySelector("textarea").value.length
会起作用。 But it seems that I cannot access elements DOM this way in ReactJS. 但是似乎我无法在ReactJS中以这种方式访问元素DOM。 Any suggestions?
有什么建议么?
You don't have to calculate the remaining characters. 您不必计算其余字符。 With the implementation you are using with a plain
textarea
tag you can just use the maxlength
attribute to specify the maximum number of characters allowed, like so: 在使用纯
textarea
标记的实现中,您可以仅使用maxlength
属性来指定允许的最大字符数,如下所示:
<textarea maxLength="100" cols="60" rows="10"></textarea>
One of the problems may be that you are executing the function by putting ()
at the end. 问题之一可能是您通过将
()
放在最后来执行函数。 So instead of setting the value to a function, you are setting the value to the function's results. 因此,不是将值设置为函数,而是将值设置为函数的结果。
So instead of this: 所以代替这个:
onKeyDown={this.charsRemaining()}
Try this: 尝试这个:
onKeyDown={this.charsRemaining}
Another thing you might try is using the synthetic event passed to the function to get the value length. 您可能尝试的另一件事是使用传递给函数的综合事件来获取值的长度。
charsRemaining( e ) {
var myTextAreaLength = e.target.value.length;
this.setState({chars: this.state.chars - myTextAreaLength});
}
I think there are other problems with the way you are constructing your component for React. 我认为您为React构建组件的方式还有其他问题。 You may want to find a tutorial of a working react component, and how they set the initial state, and bind functions to events.
您可能想找到一个有关反应组件正常工作的教程,以及它们如何设置初始状态以及将函数绑定到事件的教程。 Or perhaps look at the answer to this question: How to get input textfield values when enter key is pressed in react js?
或者也许看一下这个问题的答案: 在react js中按下Enter键时如何获取输入文本字段值?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.