简体   繁体   English

从输入中未调用onChange方法

[英]onChange method not getting called from input

I am having a button from which I open the file explorer. 我有一个从中打开文件浏览器的按钮。 I am doing it like this 我这样做

 {
   this.props.fileUploadIsOpen
      && <div className='assign-dialog'>
          <div className='assign-dialog-inner'>
             <div className='dia-title'> File Upload</div>
                <div className='dia-body'>
                   <div className='control-container'>
                       <div className='control-label'> Video File</div>
                           <div className='control'>
                             <input type="text" className="form-control" id="usr"/>
                             <button type="button" className="btn btn-primary" onClick={(e) => this.upload.click()}>Browse</button>
                             <input id="myInput" type="file" ref={(ref) => this.upload = ref} style={{visibility: 'hidden', width:0}} onChange={this.handleFileSelect}/>
                           </div>
                       </div>

But onChange method is not getting called. 但是onChange方法没有被调用。 When I select a file, nothing happens. 当我选择一个文件时,什么也没有发生。 onChange method is supposed to called handleFileSelect function, which prints the file name in console. onChange方法应该调用handleFileSelect函数,该函数在控制台中打印文件名。 But nothing happens in console. 但是控制台中什么也没有发生。 Is onChange not getting triggered? 是否未触发onChange? How can I solve it? 我该如何解决?

I do not know why you are passing a function to the ref attr, but I have recreated your case and it nails what you want 我不知道您为什么要向ref attr传递函数,但是我已经重新创建了您的案例,它可以满足您的需求

class Uploader extends React.Component {
    constructor () {
        super();
    }

    onClick (e) {
        const {fileUpload} = this.refs;
        fileUpload.click();
    }
    // prints the file name
    handleFileSelect (e) {
        const {fileUpload} = this.refs;
        console.log(fileUpload.files[0].name)
    }
    render () {
        return (
            <div>
                <div className='control-label'> Video File</div>
                <div className='control'>
                    <input type="text" className="form-control" id="usr"/>
                    <button 
                    type="button" 
                    className="btn btn-primary" 
                    onClick={this.onClick.bind(this)}>Browse</button>
                    <input id="myInput" type="file" ref="fileUpload" style={{visibility: 'hidden', width:0}} onChange={this.handleFileSelect.bind(this)}/>
                </div>
            </div>
        );
    }
}

因为您没有在此处调用handleFileSelect函数,而是由eventListener调用,所以需要将其绑定,例如以下代码:

this.handleFileSelect.bind(this)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM