admin管理员组文章数量:1399466
Please take a look at this simple fiddle.
It is a single react ponent, which is a textarea. It displays a counter below the textarea.
The goal is to have the counter update onChange
to reflect the new value (total text area length).
Unfortunately, my counter dissappears whenever a change happens. I suspect my this
or syntax is off specifically in the middle of this code block:
recalculate() {
this.setState({
text: this.state.text.length
});
}
But React is a new beast and so is ES6. What am I missing here?
Please take a look at this simple fiddle.
It is a single react ponent, which is a textarea. It displays a counter below the textarea.
The goal is to have the counter update onChange
to reflect the new value (total text area length).
Unfortunately, my counter dissappears whenever a change happens. I suspect my this
or syntax is off specifically in the middle of this code block:
recalculate() {
this.setState({
text: this.state.text.length
});
}
But React is a new beast and so is ES6. What am I missing here?
Share Improve this question edited Jan 5, 2016 at 17:37 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked Jan 5, 2016 at 16:49 ilreinilrein 3,9234 gold badges32 silver badges50 bronze badges 2- what does your initial state look like? – Stephen Burke Commented Jan 5, 2016 at 16:51
- Accidentally put in the wrong link. Updated now. State is set with this.state = { text: "hello from @merlo!" }; – ilrein Commented Jan 5, 2016 at 16:52
4 Answers
Reset to default 2You should set state
with new value, because now you always set default state
value
recalculate(e) {
this.setState({
text: e.target.value
});
}
Example
Your problem is you rely on this.state.text to populate your textarea. Once you type and call recalculate() you change this.state.text to an int and then try and call .length on this int and this causes the value to be undefined. I would remend this: https://jsfiddle/74jufckm/1/
recalculate( event ) {
this.setState({
text: event.target.value,
textLength: event.target.value.length
});
}
You were also never setting the state of the text again when recalculating.
The problem is with your recalculate function. You need to setState the new textarea value. Code like below should fix it
recalculate({target: {value}}) {
this.setState({
text: value
});
}
Here is a JSfiddle with working code
You want to update the value of the textbox. Try using e.target.value
as the state.
https://jsfiddle/Lz5v8gq9/3/
本文标签: javascriptReactES6Dynamically watching the total character length of a textareaStack Overflow
版权声明:本文标题:javascript - React - ES6 - Dynamically watching the total character length of a textarea - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744168819a2593677.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论