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
Add a ment  | 

4 Answers 4

Reset to default 2

You 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