来自此处的良好文档和示例,解释了您正在尝试做什么。
https://reactjs.org/docs/uncontrolled-components.html#the-file-input-tag
代码笔: https ://codepen.io/anon/pen/LaXXJj
React.JS 包含要使用的特定文件 API。
以下示例显示了如何创建对 DOM 节点的引用以访问提交处理程序中的文件:
HTML
<input type="file" />
React.JS
class FileInput extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.fileInput = React.createRef();
}
handleSubmit(event) {
event.preventDefault();
alert(
`Selected file - ${
this.fileInput.current.files[0].name
}`
);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Upload file:
<input type="file" ref={this.fileInput} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
}
ReactDOM.render(
<FileInput />,
document.getElementById('root')
);
警报文件名
alert(`Selected file - ${this.fileInput.current.files[0].name}`);
引用:React.JS 文档 | 例子