ant-design-vue/components/vc-form/demo/file-input.js

86 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-05-04 04:16:17 +00:00
/* eslint react/no-multi-comp:0, no-console:0 */
2019-01-12 03:33:27 +00:00
import { createForm } from '../index';
import { regionStyle, errorStyle } from './styles';
2018-05-04 04:16:17 +00:00
2019-01-12 03:33:27 +00:00
function getFileValueProps(value) {
2018-05-04 04:16:17 +00:00
if (value && value.target) {
return {
value: value.target.value,
2019-01-12 03:33:27 +00:00
};
2018-05-04 04:16:17 +00:00
}
return {
value,
2019-01-12 03:33:27 +00:00
};
2018-05-04 04:16:17 +00:00
}
2019-01-12 03:33:27 +00:00
function getValueFromFileEvent({ target }) {
2018-05-04 04:16:17 +00:00
return {
target,
2019-01-12 03:33:27 +00:00
};
2018-05-04 04:16:17 +00:00
}
const Form = {
props: {
form: Object,
},
methods: {
2019-01-12 03:33:27 +00:00
onSubmit(e) {
e.preventDefault();
2018-05-04 04:16:17 +00:00
this.form.validateFields((error, values) => {
2019-01-12 03:33:27 +00:00
console.log(error, values);
2018-05-04 04:16:17 +00:00
if (!error) {
2019-01-12 03:33:27 +00:00
console.log('校验通过');
2018-05-04 04:16:17 +00:00
}
2019-01-12 03:33:27 +00:00
});
2018-05-04 04:16:17 +00:00
},
2019-01-12 03:33:27 +00:00
checkSize(rule, value, callback) {
2018-05-04 04:16:17 +00:00
if (value && value.target) {
2019-01-12 03:33:27 +00:00
const files = value.target.files;
2018-05-04 04:16:17 +00:00
if (files[0]) {
2019-01-12 03:33:27 +00:00
callback(files[0].size > 1000000 ? 'file size must be less than 1M' : undefined);
2018-05-04 04:16:17 +00:00
} else {
2019-01-12 03:33:27 +00:00
callback();
2018-05-04 04:16:17 +00:00
}
} else {
2019-01-12 03:33:27 +00:00
callback();
2018-05-04 04:16:17 +00:00
}
},
},
2019-01-12 03:33:27 +00:00
render() {
const { getFieldProps, getFieldError } = this.form;
const errors = getFieldError('attachment');
return (
<div style={regionStyle}>
<div>attachment:</div>
<div>
<input
type="file"
{...getFieldProps('attachment', {
getValueProps: getFileValueProps,
getValueFromEvent: getValueFromFileEvent,
rules: [this.checkSize],
})}
/>
</div>
<div style={errorStyle}>{errors ? errors.join(',') : null}</div>
<button onClick={this.onSubmit}>submit</button>
2018-05-04 04:16:17 +00:00
</div>
2019-01-12 03:33:27 +00:00
);
2018-05-04 04:16:17 +00:00
},
2019-01-12 03:33:27 +00:00
};
2018-05-04 04:16:17 +00:00
2019-01-12 03:33:27 +00:00
const NewForm = createForm()(Form);
2018-05-04 04:16:17 +00:00
export default {
2019-01-12 03:33:27 +00:00
render() {
return (
<div>
<h2>input[type="file"]</h2>
<NewForm />
</div>
);
2018-05-04 04:16:17 +00:00
},
2019-01-12 03:33:27 +00:00
};