我有一个文件选择器,当点击按钮时,文件选择器就会出现:
<input id='example' type="file" accept="image/*" onChange={this.onImageChange} />现在我想使用另一个按钮来做这件事,触发上面的输入:
<button onClick={() => {
var element = document.getElementById('example');
console.log(element) // This shows <input id="example" type="file" accept="image/*">
// element.onChange() // Error: onChange() is not a function
// Above doesn't work, so I try to trigger the onChange event manually,
// but below doesn't do anything
var event = new Event('change');
element.dispatchEvent(event);
}}></button>发布于 2019-02-14 05:36:33
如果是react,就不应该访问Dom来获取这些东西。他们有一个Api来满足你的需求。
您需要一个非控制器组件。为了做到这一点,你可以使用一个引用。
我还没试过,但我认为你能做到。
在构造函数上创建ref
this.inputRef = React.createRef();然后将输入ref prop赋值给this.inputRef
<input ref={this.inputRef} id='example' type="file" accept="image/*" onChange={this.onImageChange} />和最近发送的点击。
this.inputRef.current.click();希望它能起作用
发布于 2019-02-14 06:58:27
element.onChange不是一种方法,因为您的onChange函数存储在react组件类中,并通过React的合成事件发射器进行委托。它是React.createElement('input')的属性,但不是实际DOM元素的属性。
要调用React元素的onChange方法,可以像this.onChange(event)一样直接调用它。
这种方法的问题是,您的事件不会附加目标。
change方法旨在提供一个用于控制输入值的接口,因此,如果要更改附加到输入的文件,只需在状态中更改其值即可。
this.setState({file: this.alternateFile}) 发布于 2019-02-14 05:33:06
https://stackoverflow.com/questions/54679691
复制相似问题