Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @desc antd Input 组件封装
- * @auth yanxi@douyu.tv
- * @date 2019/5/21
- */
- import React, { Component } from 'react';
- import AntdInput from 'antd/lib/input';
- // import Form from 'antd/lib/form';
- import {
- string, object, bool, func,
- } from 'prop-types';
- import FormItem from '../Form/FormItem';
- // const FormItem = Form.Item;
- const defaultId = `${Math.random()}`;
- class Input extends Component {
- static propTypes = {
- label: string,
- id: string,
- labelCol: object,
- wrapperCol: object,
- visibility: bool,
- getValue: func,
- };
- static defaultProps = {
- label: '默认label',
- id: defaultId,
- labelCol: {},
- wrapperCol: {},
- visibility: true,
- getValue: () => {},
- };
- constructor(props) {
- super(props);
- this.firstIn = 1;
- this.value = props.value;
- }
- componentWillReceiveProps(nextProps) {
- const { id, value, form: { setFieldsValue } } = nextProps;
- const update = this.updateValue(value);
- this.firstIn = 0;
- if (update) {
- setFieldsValue({
- [id]: value,
- });
- }
- }
- checkValue = () => {
- const { id, form: { getFieldValue } } = this.props;
- const newValue = getFieldValue(id || defaultId);
- const update = this.updateValue(newValue);
- if (update) {
- this.onChange({
- target: {
- value: newValue,
- },
- });
- }
- }
- updateValue = (newValue) => {
- let update = 0;
- if (newValue !== this.value) {
- this.value = newValue;
- update = 1;
- }
- return update;
- }
- onChange = (e) => {
- const { onChange } = this.props;
- if (onChange) {
- onChange(e.target.value, e);
- }
- }
- render() {
- const {
- label, id, labelCol, wrapperCol, getValue,
- rules = {}, visibility, batchStyle, formStyle,
- form: { getFieldDecorator },
- remarks, $form, propsConfig, permissions, $formPermissions,
- ...others
- } = this.props;
- const targetRules = [];
- const formLayout = {
- labelCol,
- wrapperCol,
- };
- if (!this.firstIn) {
- this.checkValue();
- }
- if (!label) {
- formLayout.labelCol.span = 0;
- formLayout.wrapperCol.span = 24;
- }
- if (rules.required) {
- targetRules.push({
- required: true, message: '此项必填',
- });
- }
- if (rules.max) {
- targetRules.push({
- max: rules.max, message: rules.maxMsg,
- });
- }
- if (rules.pattern) {
- targetRules.push({
- pattern: new RegExp(rules.pattern), message: rules.message,
- });
- }
- if (!visibility) {
- return null;
- }
- delete others.value;
- return (
- <FormItem
- {...formLayout}
- label={label}
- style={Object.assign({}, batchStyle || {}, formStyle || {})}
- remarks={remarks}
- >
- {getFieldDecorator(id || defaultId, {
- initialValue: others.defaultValue,
- rules: targetRules,
- })(
- <AntdInput
- {...others}
- onPressEnter={() => {
- if (getValue) {
- getValue();
- }
- }}
- onChange={this.onChange}
- />,
- )}
- </FormItem>
- );
- }
- }
- export default Input;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement