本文介绍了如何在文件选择器中获取文件名反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我如何在文件选择器中获取文件名吗?从文件选择器中选择文件后,我试图在输入字段中设置值这是我的代码https://stackblitz.com/edit/react-d4kp1d?file=bulk.js我是这样试的

{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 chooserhere is my codehttps://stackblitz.com/edit/react-d4kp1d?file=bulk.jsI 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:

<input type="file" />
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}`);

Cited: React.JS Documentation | Examples

这篇关于如何在文件选择器中获取文件名反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 13:42
查看更多