如何在文件选择器中获取文件名反应? [英] how get get file name in file chooser in react?
问题描述
你能告诉我如何在文件选择器中获取文件名吗?从文件选择器
中选择文件后,我试图在输入字段中设置值这是我的代码https://stackblitz.com/edit/react-d4kp1d?file=bulk.js我是这样试的
<输入id="file_input_file"类名=无"类型=文件"参考={输入参考}onChange={(e)=>{console.log('---')console.log(inputRef.current[0].files[0].name)}}/>
它给了我 undefined
来自此处的优秀文档和示例,解释了您正在尝试做什么.https://reactjs.org/docs/uncontrolled-components.html#the-file-input-tag
Codepen: https://codepen.io/anon/pen/LaXXJj
React.JS 包含要使用的特定文件 API.
以下示例显示如何创建对 DOM 节点的引用以访问提交处理程序中的文件:
<块引用>HTML
<块引用>
React.JS
class FileInput extends React.Component {构造函数(道具){超级(道具);this.handleSubmit = this.handleSubmit.bind(this);this.fileInput = React.createRef();}处理提交(事件){event.preventDefault();警报(`选定的文件 - ${this.fileInput.current.files[0].name}`);}使成为() {返回 (<form onSubmit={this.handleSubmit}><标签>上传文件:<input type="file" ref={this.fileInput}/>标签><br/><button type="submit">提交</button></表单>);}}ReactDOM.render(<文件输入/>,document.getElementById('root'));
<块引用>
警报文件名
alert(`选定的文件 - ${this.fileInput.current.files[0].name}`);
引用:React.JS 文档 |示例
could you please tell me how get get file name in file chooser in react ?
I am trying to set value in input field after choosing file from file chooser
here is my code
https://stackblitz.com/edit/react-d4kp1d?file=bulk.js
I tried like this
<input
id="file_input_file"
className="none"
type="file"
ref={inputRef }
onChange={(e)=>{
console.log('---')
console.log(inputRef.current[0].files[0].name)
}}
/>
it gives me undefined
Good documentation and example taken from here, explaining what you are trying to do. https://reactjs.org/docs/uncontrolled-components.html#the-file-input-tag
Codepen: https://codepen.io/anon/pen/LaXXJj
React.JS contains a specific File API to use.
The following example shows how to create a ref to the DOM node to access file(s) in a submit handler:
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 Filename
alert(`Selected file - ${this.fileInput.current.files[0].name}`);
Cited: React.JS Documentation | Examples
这篇关于如何在文件选择器中获取文件名反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!