我自己写了个imageEdit的组件,代码如下:
import React from 'react';
import constant from '../../../constant/constant';
import {generateHibikiUrl, getRandomValue} from '../../../util/util';
import Icon from '../../common/misc/Icon.react';
class ImageEdit extends React.Component {
constructor(props) {
super(props);
this.state = {
file: null,
imagePreviewUrl: null,
rand: getRandomValue()
};
}
updateData(file) {
var {item, uploadFile} = this.props;
var itemId = item.id;
var file = this.state.file;
item['imagePreviewUrl'] = this.state.imagePreviewUrl;
var value = {
file: file
};
uploadFile(item, file);
}
handleImageChange(e) {
e.preventDefault();
var reader = new FileReader();
var file = e.target.files[0];
reader.onloadend = () => {
this.setState({
file: file,
imagePreviewUrl: reader.result
});
this.updateData();
};
reader.readAsDataURL(file);
}
deleteImage() {
this.setState({
file: null,
imagePreviewUrl: null
});
this.props.deleteImage(this.props.item);
}
render() {
var {binderId, documentId, item, isPreview} = this.props;
var itemId = item.id;
if(this.props.isPreview){
var url = this.props.item.imagePreviewUrl;
}else {
var url = item.value && item.value.name ? generateHibikiUrl(`CABImageDownload.do?binderId=${binderId}&itemId=${itemId}&recordId=${documentId}&${this.state.rand}`) : null;
}
var loading = item.status === constant.STATUS_UPDATING ?
<Icon icon='spin' className='orange'/> : null;
var uploadButton = <input type='file' onChange={(e) => this.handleImageChange(e)}/>;
var img = url ? <img src={url} className='img-block'/> : null;
var deleteButton = url ?
<div className='delete-pink' onClick={this.deleteImage.bind(this)}>
<Icon icon='delete'/>
</div> : null;
return (
<div>
<div className='img-loading-block'>
{img}
{loading}
{deleteButton}
</div>
{uploadButton}
</div>
);
}
}
ImageEdit.propTypes = {
application: React.PropTypes.object.isRequired,
item: React.PropTypes.object.isRequired,
binderId: React.PropTypes.string.isRequired,
documentId: React.PropTypes.string.isRequired,
updateItemValue: React.PropTypes.func.isRequired,
deleteImage: React.PropTypes.func.isRequired,
uploadFile: React.PropTypes.func.isRequired
};
ImageEdit.displayName = 'ImageEdit';
export default ImageEdit;
我把这个组件放进一个view里,我通过拖动调节屏幕的大小,这个时候这个组件就会重新加载,但是值却没有保存住,怎么解决啊,急死了!
效果如下:
刚上传上来的时候,有文件名字
然后我手动拖大了屏幕大小,文件名字就没有了
props如下:
还有一个问题,我删除图片之后,图片没了,但是图片的名字却还在,怎么办啊
ImageEdit中重写shouldComponentUpdate方法,根据你自己的逻辑进行判断,如果不需要ImageEdit重新渲染(render),就返回false。比如你在shouldComponentUpdate中判断this.props === nextProps,就返回false。具体逻辑要取决于你自己的业务。