setState()
处理程序中的onChange
方法调用导致了中止。```
import React from 'react';
import ReactDOM from 'react-dom';
import { Upload, Form, Icon } from 'antd';
function getBase64(img, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
}
class AddBookForm extends React.Component {
state = {
loading: false,
};
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.
getBase64(info.file.originFileObj, imageUrl => this.setState({
imageUrl,
loading: false,
}));
}
}
render() {
const formItemLayout = { labelCol: { xs: 24, sm: 2 }, wrapperCol: { xs: 24, sm: 8 } };
const FormItem = function(props) {
return <Form.Item {...formItemLayout} {...props}></Form.Item>;
};
const uploadButton = (
<div>
<Icon type={this.state.loading ? 'loading' : 'plus'} />
<div className="ant-upload-text">Upload</div>
</div>
);
const imageUrl = this.state.imageUrl;
return (
<Form layout="horizontal">
<FormItem label="图片" extra="请上传2M以内的JPG图片">
<Upload
name='imageFile'
action="/api/image-upload"
onChange={this.handleChange}
showUploadList={false}
listType="picture-card"
className="single-image-uploader"
>
{imageUrl ? <img src={imageUrl} alt="" /> : uploadButton}
</Upload>
</FormItem>
</Form>
);
}
}
ReactDOM.render((
<AddBookForm />
), document.getElementById('root'));
将<FormItem>
组件从无状态功能组件更改为类组件后,此问题得以解决。
class FormItem extends React.Component {
render() {
const formItemLayout = { labelCol: { xs: 24, sm: 2 }, wrapperCol: { xs: 24, sm: 8 } };
return <Form.Item {...formItemLayout} {...this.props}></Form.Item>
}
}