如何通过在 ReactJS 中单击另一个按钮在 <input type='file' /> 上触发 onChange?

新手上路,请多包涵
<div style={{display: 'grid'}}>
    <button id='plus' onClick={???}>+</button>
    <input id='selectImage' type="file" onChange={fileSelectHandler} />
</div>

在这里,我想通过单击按钮来触发输入的 onChange 函数。如何解决这个问题?

原文由 techKid-Rinshad 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 517
2 个回答

您可以隐藏原始文件输入,并在单击按钮时通过 javascript 使其单击。

 upload() {
  document.getElementById("selectImage").click()
}

<div style={{display: 'grid'}}>
  <button id='plus' onClick={this.upload}>+</button>
  <input id='selectImage' hidden type="file" onChange={fileSelectHandler} />
</div>

原文由 McRist 发布,翻译遵循 CC BY-SA 4.0 许可协议

创建一个参考:

 //inside the constructor:
fileRef = React.createRef()
// in your input element
<input id='selectImage' type="file" onChange={fileSelectHandler} ref={this.fileRef} />

现在,

 <button id='plus' onClick={this.triggerClick}>+</button>

triggerClick() {
  this.fileRef.current.click()
}

原文由 Bhojendra Rauniyar 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题