简体   繁体   中英

React JS view not re-rendering on setState()

Using react js 0.13.1 and es6 with babel:

I have a file input and a textarea, I want the user to be able to select text files and have the text append to the textarea.

When the onChange event fires, it uses the FileReader API to read the file as text, then calls setState({text: <text from the file>}) . That's working fine.

The problem is that when you select and open a file, nothing happens to the text in the textarea... it just keeps whatever text it was initialized with. It seems like react either isn't updating the view after setState() , or maybe I just misspelled something. Not sure yet, but any help is appreciated!

here's my (simplified) code:

'use strict';

class TextApp extends React.Component {
  constructor() {
    this.state = {
      text: 'wow'
    };
  }

  readFile(e) {
    var self = this;
    var files = e.target.files;

    for (var i = 0, len = files.length; i < len; i++) {
      var reader = new FileReader();

      reader.onload = function(upload) {
        var textState = (self.state.text || '') + upload.target.result;
        self.setState({
          text: textState
        });
      };
      reader.readAsText(files[i]);
    }
  }

  render() {
    return (
      <div>
        <TextInput text={this.state.text} />
        <FileInput onChange={this.readFile} />
      </div>
    );
  }
}

class TextInput extends React.Component {
  render() {
    return (
      <textarea>{this.props.text}</textarea>
    );
  }
}

class FileInput extends React.Component {
  render() {
    return (
      <div>
          <input type="file" onChange={this.props.onChange} multiple />
      </div>
    );
  }
}

React.render(<TextApp />, document.getElementById('reappct'));

Use <textarea value={this.props.text} /> . See Why Textarea Value? :

If you do decide to use children, they will behave like defaultValue .

Along with what @BinaryMuse has suggested, you also have to bind readFile method like this

<FileInput onChange={this.readFile.bind(this)} />

Here is the updated demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM