共计 2482 个字符,预计需要花费 7 分钟才能阅读完成。
React- 图片输入框 - 移动端网页
gitHub 地址 觉得有参考价值,点个赞
https://github.com/xiaopingzh…
目录结构
.
├── README.md
├── dist
│ ├── bundle.js
│ └── index.html
├── package.json
├── src
│ ├── components
│ │ ├── ErrorPage
│ │ │ ├── ErrorPage.css
│ │ │ └── ErrorPage.js
│ │ ├── Notice
│ │ │ ├── Notice.css
│ │ │ └── Notice.js
│ │ ├── PersonalUploadFileForm
│ │ │ ├── PersonalUploadFileForm.css
│ │ │ └── PersonalUploadFileForm.js
│ │ ├── SuccessPage
│ │ │ ├── SuccessPage.css
│ │ │ └── SuccessPage.js
│ │ └── common
│ │ ├── actions.js
│ │ ├── getUrlpargm.js
│ │ └── utils.js
│ ├── index.html
│ ├── index.js
│ └── page
│ ├── UploadForm.js
│ └── upLoadForm.css
├── webpack.config.js
└── webpack.production.config.js
上传组件代码
基于原生的 API 接口,点击输入输入框 手机上会出现 文件 相机选项 可自行选择拍照上传,为解决微信内置上传的 bug 其中 accept 设置为 accept=”image/*”
loading 组件找了一个简单的动效
npm config set ‘@bit:registry’ https://node.bit.dev
npm i @bit/davidhu2000.react-spinners.pulse-loader
来源
https://bit.dev/davidhu2000/r…
import React from ‘react’;
import ‘./PersonalUploadFileForm.css’;
import toast from ‘../Notice/Notice’;
import PulseLoader from ‘@bit/davidhu2000.react-spinners.pulse-loader’;
class PersonalUploadFileForm extends React.Component {
constructor(props) {
super(props);
this.state = {
filePreviewUrl: this.props.value ? this.props.value.base64 : ”,
overSizeModel: false,
};
}
selectFile = e => {
e.preventDefault();
this.refs.fileinput.click();
};
_handleFileChange = e => {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
if (file.type != ‘image/jpeg’ && file.type != ‘image/png’) {
toast(‘ 请选择图片 ’,”error”);
return false;
}
if (file.size > 8000000){
toast(‘ 图片太大, 请重新选择 ’,”error”);
return false;
}
this.setState({
filePreviewUrl: reader.result,
});
this.props.onChange({name: file.name, base64: reader.result});
};
reader.readAsDataURL(file);
e.target.value = null;
};
render() {
let {filePreviewUrl} = this.state;
let {backimg, textTip, displaybackimg, uploading} = this.props;
return (
<div className=”uploadpicture”>
<div>
<div className=”uploadpictureimg” onClick={this.selectFile}>
<div className=”img-preshow”>
{uploading ? (
<div
className=”img-preshow-loading”
style={{
backgroundImage: `url(${filePreviewUrl})`,
opacity:”0.7″
}}
>
<div style={{position: ‘relative’, display: ‘inline’, lineHeight: ‘2.62rem’}}>
<PulseLoader size={0.16} margin={‘0.2rem’} color=”#5f87f8″ sizeUnit=”rem” />
</div>
</div>
) : (
<img
src={displaybackimg ? filePreviewUrl : backimg}
style={{width: ‘100%’, height: ‘100%’}}
/>
)}
</div>
</div>
<div>
<input
type=”file”
ref=”fileinput”
onChange={this._handleFileChange}
style={{display: ‘none’}}
accept=”image/*”
/>
</div>
</div>
{textTip && <span className=”textTippict”>{textTip}</span>}
</div>
);
}
}
export default PersonalUploadFileForm;
初试界面
— 选择图片
- 上传失败提示
上传中
上传成功
微信内置浏览器打开