javascript - React JS view not re-rendering on setState() -
using react js 0.13.1 , es6 babel:
i have file input , textarea, want user able select text files , have text append textarea.
when onchange event fires, uses filereader api read file text, calls setstate({text: <text file>})
. that's working fine.
the problem when select , open file, nothing happens text in textarea... keeps whatever text initialized with. seems react either isn't updating view after setstate()
, or maybe misspelled something. not sure yet, appreciated!
here's (simplified) code:
'use strict'; class textapp extends react.component { constructor() { this.state = { text: 'wow' }; } readfile(e) { var self = this; var files = e.target.files; (var = 0, len = files.length; < 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'));
along @binarymuse has suggested, have bind readfile
method
<fileinput onchange={this.readfile.bind(this)} />
here updated demo