封装上传图片组件
一、自定义或第三方的表单控件遵循以下的约定:
提供受控属性 value 或其它与 valuePropName 的值同名的属性。
提供 onChange 事件或 trigger 的值同名的事件。
二、getDerivedStateFromProps生命周期
React生命周期的命名一直都是非常语义化的,这个生命周期的意思就是从props中获取state,可以说是太简单易懂了。
可以说,这个生命周期的功能实际上就是将传入的props映射到state上面。
由于16.4的修改,这个函数会在每次re-rendering之前被调用,这意味着什么呢?
意味着即使你的props没有任何变化,而是父state发生了变化,导致子组件发生了re-render,
这个生命周期函数依然会被调用。看似一个非常小的修改,却可能会导致很多隐含的问题。
使用方法
这个生命周期函数是为了替代componentWillReceiveProps存在的,所以在你需要使用componentWillReceiveProps的时候,就可以考虑使用getDerivedStateFromProps来进行替代了。
两者的参数是不相同的,而getDerivedStateFromProps是一个静态函数,也就是这个函数不能通过this访问到class的属性,也并不推荐直接访问属性。而是应该通过参数提供的nextProps以及prevState来进行判断,根据新传入的props来映射到state。
需要注意的是,如果props传入的内容不需要影响到你的state,那么就需要返回一个null,这个返回值是必须的,所以尽量将其写到函数的末尾。
import React from "react"
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Upload, message } from 'antd';//引入的antd封装好的Upload组件,相当于我们进行二次封装
function beforeUpload(file) {//判断文件类型
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('You can only upload JPG/PNG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {//判断上传文件大小
message.error('Image must smaller than 2MB!');
}
return isJpgOrPng && isLt2M;
}
class upload extends React.Component {
static defaultProps = {
value: ''
}
state = {
loading: false,
imageUrl: this.props.value
};
static getDerivedStateFromProps(nextProps, state) {
if (nextProps.value !== state.imageUrl) {
return {
imageUrl: nextProps.value
}
}
return null
}
handleChange = info => {
if (info.file.status === 'uploading') {
this.setState({ loading: true });
return;
}
if (info.file.status === 'done') {
// Get this url from response in real world.
console.log(info, 'ifo')
const response = info.file.response;
// console.log(response,'123456');
/**
* base: "/public/assets/upload/"
code: 1
msg: "success"
origin: "http://148.70.121.59:9001"
urls: Array(1)
0: {filename: "0432f11ccb974628.jpg", imgurl: "e6329a2ccf7e115f.jpg"}
*/
//onChange 上传中、完成、失败都会调用这个函数。
this.props.onChange(response.origin + response.base + response.urls[0].imgurl)
this.setState({
loading: false,
})
}
};
render() {
const uploadButton = (
<div>
{this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
<div className="ant-upload-text">Upload</div>
</div>
);
const { imageUrl } = this.state;
return (
<Upload
name="avatar"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
action="/farmland/img/upload"
beforeUpload={beforeUpload}
onChange={this.handleChange}
>
{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
</Upload>
)
}
}
export default upload
本文由博客群发一文多发等运营工具平台 OpenWrite 发布