抱歉,标题令人困惑。
基本上,我有一个包含单个输入的表单,该输入带有伪装为图标的类型文件
我希望在选择文件时提交表单,但是我不知道如何使用输入onChange事件调用表单提交(我什至不知道这样做是否足够)。
这是代码:
<Form onSubmit={handleSubmit((data) => updateProfilePicture(data))}>
<IconButton
component='label'
htmlFor='image-input'
style={{
position: "absolute",
bottom: "0",
right: "0",
backgroundColor: "#eee",
}}
>
<Input
type='file'
id='image-input'
name='file'
style={{ display: "none" }}
inputRef={register}
/>
<PhotoCameraIcon style={{ fontSize: "25px" }} />
</IconButton>
</Form>
这里看起来像:
注意:有两种形式,一种用于图像,一种用于数据,我不想通过“更新”按钮来处理,否则它将仅是一种形式,而我不会遇到这个问题
添加图像后,您无需提交表单。
您可以只使用输入字段并添加onChange事件处理程序以获取Image详细信息。如果有兴趣请检查一下
https://stackblitz.com/edit/react-qjqt3f
import React from "react";
import "./style.css";
export default class App extends React.Component {
constructor() {
super();
this.state = {
url: "https://www.w3schools.com/howto/img_avatar.png"
};
}
onSelectFile = e => {
if (e.target.files && e.target.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(e.target.files[0]); // read file as data url
reader.onload = event => {
// called once readAsDataURL is completed
console.log(event.target.result);
this.setState({ url: event.target.result });
//you can do the HTTP post call here
};
}
};
render() {
return (
<div>
<label className="hoverable" htmlFor="fileInput">
<img src={this.state.url} />
<div className="hover-text">Choose file</div>
<div className="background" />
</label>
<br />
<input id="fileInput" type="file" onChange={this.onSelectFile} />
</div>
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句