我需要手动触发 onChange
<input type="file">
上的事件用户单击重置按钮后的元素。我有一个复杂的表单,其中包含 20 多个输入并允许动态添加新输入,其处理由我的容器组件(未显示)中的顶级函数处理,该函数接受每个输入的更改事件并弄清楚如何改变我的状态。
在页面加载时,我调用 API 并使用数据预填充表单。根据查询的内容,这有时可能包括英雄形象。如果图像存在,我会使用“单击以删除/更改”按钮来显示它。单击此按钮会触发输入上的 onChange 事件,该事件沿 React 树向上流动并更新我的“内容”状态(在本例中删除 hero_image 对象中的数据)。
我已尝试将该值设置为 null,但因为该值在页面加载时已经为 null,所以它似乎没有触发 onChange 事件。我也尝试过以不同的方式手动触发事件。出于安全原因,您无法以与文本输入相同的方式预填充文件输入的值,因此我正在努力找出解决此问题的最佳方法。
export default class ImageUpload extends Component {
handleImageChange(e) {
console.log('change');
this.props.onChange(e);
}
removeImage = (e) => {
e.preventDefault();
// Setting the value to null doesn't trigger the onChange event
this.inputElement.value = null;
// Below is an attempt to manually trigger the onChange event using the input ref
const changeEvent = new Event('change');
this.inputElement.dispatchEvent(changeEvent);
}
render() {
const { name, label, value, children, error } = this.props;
return (
<div>
{label &&
<label htmlFor={name}>{label}</label>
}
{children}
<div className="image-upload-preview">
<Button onClick={e => this.removeImage(e)}>Click to remove/change</Button>
<img alt="" src={value.data.src} />
</div>
<button className="form-control image-upload-btn" onClick={this.fakeButtonClick}>
<IconWithText text="Click to add an image from your device (JPEG, PNG, GIF)" iconName="insert-image" iconSize="M" iconFill="dark" />
<input
id="eugh"
type="file"
name={name}
ref={(input) => { this.inputElement = input; }}
accept="image/jpeg, image/png, image/gif"
onChange={e => this.handleImageChange(e)}
onClick={e => e.stopPropagation()}
/>
</button>
</div>
);
}
}
最佳答案
在您的 onChange 中,您应该将文件名保存到状态(e.target.value
我相信)并将其设置为输入的 value
属性。如果选择另一个文件,它将触发 onChange。然后在重置按钮上,如果将状态更改为 null,它不会触发 onChange 事件吗?
即
state = {
filename: '',
}
<input value={this.state.filename} ... />
handleImageChange(e) {
this.setState({ filename: e.target.value });
}
handleFormReset() {
this.setState({ filename: '' });
}
关于javascript - React - 在 <input type ="file"> 上手动触发 onChange 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46321065/