【问题标题】:Flatbutton(Input handler) doesn't seems to workFlatbutton(输入处理程序)似乎不起作用
【发布时间】:2017-08-24 05:45:29
【问题描述】:
我尝试使用 materila-ui 的文件上传器,但它似乎不起作用并从选择文件中获取输入。
任何人都对如何从文件选择器获取输入并处理它有任何建议。
<FlatButton
icon={<i className="material-icons">attachment</i>}
onclick={e => this._handleChange(e)}
onchange={e => this._openFileDialog(e)}
>
<input type="file" style={styles.uploadInput} />
</FlatButton>
http://material-ui.com/#/components/flat-button
【问题讨论】:
标签:
javascript
html
reactjs
material-design
material-ui
【解决方案1】:
不要在FlatButton上定义onChange事件,而是在input元素上定义它,这样写:
<FlatButton
icon={<i className="material-icons">attachment</i>}
onClick={e => this._handleChange(e)}
>
<input type="file" onChange={this._handleFileUpload.bind(this)}/>
</FlatButton>
然后在onChange方法中使用e.target.files,就可以访问选中的文件了:
_handleFileUpload(e){
console.log(e.target.files);
}
【解决方案2】:
您应该将按钮包装在标签中,并将其指向可以隐藏的文件输入。
<label htmlFor={id}>
<FlatButton />
</label>
<input type="file" id={id} onChange={(e) => {
const file = e.target.files[0];
// do stuff
}}
在构造函数中生成一个随机 id 以在此处使用。