ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

antd笔记

2022-04-06 17:33:28  阅读:400  来源: 互联网

标签:控件 string render value 笔记 props antd options


const { getFieldDecorator, getFieldValue, setFieldsValue, resetFields, validateFields, getFieldError } = this.props.form;

getFieldDecorator:

用于和表单进行双向绑定

getFieldDecorator(id, options) 参数

id

必填输入控件唯一标志。支持嵌套式的写法。string

options.getValueFromEvent
可以把 onChange 的参数(如 event)转化为控件的值

function(..args)

<FormItem>
商品名称:
	{getFieldDecorator('itemName', {
		initialValue: undefined,
		getValueFromEvent: (e) => e.target.value.trim(),
		rules: [
			{ required: false },
		],
	})(
		<Input placeholder='请输入商品名称' style={{ width: 200, marginLeft: '10px' }} allowClear />
	)}
</FormItem>

options.initialValue

子节点的初始值,类型、可选值均由子节点决定(注意:由于内部校验时使用 === 判断是否变化,建议使用变量缓存所需设置的值而非直接使用字面量)

options.normalize

转换默认的 value 给控件,一个选择全部的例子

function(value, prevValue, allValues): any

options.preserve

即便字段不再使用,也保留该字段的值

boolean

options.rules

object[]

options.trigger

收集子节点的值的时机

string

'onChange'

{
                  getFieldDecorator(`content.configContentList[${index}].config`, {
                              initialValue: getUrlParam2('id') ?
                                configContentList && configContentList[index] && configContentList[index].configType == item.value :
                                true,
                              trigger: "onChange",
                              valuePropName: 'checked',
                              rules: [{
                                required: true,
                                message: '请选择配置内容',
                              }]
                            })(
                              <Checkbox onChange={this.honChangeChecked.bind(this, index, item)} key={index}>{item.name}</Checkbox>
                            )
                          }

options.validateFirst

当某一规则校验不通过时,是否停止剩下的规则的校验

boolean
false

<Form.Item label='线下活动名称' {...formLayout}>
                {
                  getFieldDecorator('jiZanPromotionConfigDTO.offActName', {
                    initialValue: (jiZanPromotionConfigDTO || {}).offActName,
                    validateFirst: true,
                    rules: [{
                      required: true, message: '请输入线下活动名称',
                    }, {
                      max: 8, min: 2, message: '线下活动名称2-8个字'
                    }]
                  })(
                    <Input disabled={promotionDisabled} type='text' placeholder='线下活动名称2-8个字' maxLength={8} style={{ width: '200px' }} />
                  )
                }
              </Form.Item>

options.validateTrigger

校验子节点值的时机
string|string[]

<FormItem label="菜单页名称" {...formItemLayout}>
            {getFieldDecorator("pageName", {
              initialValue: detailModel ? detailModel.pageName : '',
              validateTrigger: "onBlur", //  validateTrigger: ['onSubmit', 'onChange'],
              rules: [
                { required: true, message: "请输入菜单页名称" }
              ]
            })(
              <Input placeholder="请输入菜单名称" ></Input>
            )}
          </FormItem>

options.valuePropName

子节点的值的属性,如 Switch 的是 'checked' string

<FormItem label="开启筛选" {...formItemLayout}>
          {getFieldDecorator('showSwitch', {
            initialValue: !!details.search || false,
            valuePropName: 'checked'
          })(<Switch />)}
        </FormItem>
{getFieldDecorator('goodsCode', {	
	initialValue: '',
})(
	<Input
		onChange={({ target }) => {
			target.value = target.value.replace(/,/g, ',');
		}}
		placeholder="支持商品编码 商品名称 通用名搜索"
	/>
)}
<Form.Item label="抽奖类型" {...formLayout}>
    {getFieldDecorator('materialConfigDTO.activityType', {
                        initialValue: materialConfigDTO.activityType ? materialConfigDTO.activityType : 1,
                        rules: [
                        {
                        required: true,
                        message: '请选择抽奖类型'
                        }
    ]
    })(
        <Select
        style={{ width: 300 }}
        disabled={!canEdit || Boolean(getUrlParam2('id'))}
        onChange={() =>
        setFieldsValue({
        'materialConfigDTO.activityName': undefined,
        'materialConfigDTO.activityMode': 0
    })
}
    >
        <Select.Option value={1}>普通抽奖</Select.Option>
<Select.Option value={4}>积分抽奖</Select.Option>
<Select.Option value={8}>红包雨</Select.Option>
</Select>
)}
    </Form.Item>

getFieldError

获取某个输入控件的 Error Function(name)

validator: (rule, value, callback) => {
                          if (getFieldValue('endTime') && moment(getFieldValue('endTime')).isBefore(value)) {
                            callback('活动开始时间必须早于结束时间');
                            return;
                          }
                          if (getFieldError('endTime')) {
                            validateFields(['endTime'], { force: true })
                          }
                          callback();
                        }
<FormItem style={{ margin: 0 }}>
                  {getFieldDecorator(`refundAmount${record.detailId}${index}`, {
                    rules: [
                      {
                        validator: this.checkRefundAmount.bind(this, index),
                      },
                    ],
                    initialValue: 0,
                  })(
                    <Input
                      style={{ width: '60px' }}
                      onChange={this.changeRefundAmount.bind(this, index, record)}
                      ref={ref => {
                        const str = `priceInput${index}`;
                        this[str] = ref;
                      }}
                      type="number"
                      disabled={
                        getFieldError(`refundCount${record.detailId}${index}`) ||
                        getFieldValue(`refundCount${record.detailId}${index}`) == 0
                      }
                    />,
                  )}
                </FormItem>

getFieldsError

获取一组输入控件的 Error ,如不传入参数,则获取全部组件的 Error Function([names: string[]])

<Button
  size="large"
  type="primary"
  disabled={hasErrors(this.props.form.getFieldsError())}
  onClick={() => this.nextStep(false)}
>
  下一步
</Button>

getFieldsValue

获取一组输入控件的值,如不传入参数,则获取全部组件的值 Function([fieldNames: string[]])

this.props.form.getFieldsValue();

getFieldValue

获取一个输入控件的值 Function(fieldName: string)

{getFieldValue('materialConfigDTO.activityType') !== 8 && (
    <Form.Item label="活动形式" {...formLayout}>
    {getFieldDecorator('materialConfigDTO.activityMode', {
                        initialValue: materialConfigDTO.activityMode,
                        rules: [
                            {
                                required: true,
                                message: '请选择活动形式'
                            }
    					]
    })(
        <Radio.Group disabled={!canEdit}>
            <Radio value={0}>转盘式</Radio>
            <Radio value={1}>xxx式</Radio>
		</Radio.Group>
	)}
    </Form.Item>
)}

isFieldsTouched

判断是否任一输入控件经历过 getFieldDecorator 的值收集时机 options.trigger

(names?: string[]) => boolean

isFieldTouched

判断一个输入控件是否经历过 getFieldDecorator 的值收集时机 options.trigger

(name: string) => boolean

isFieldValidating

判断一个输入控件是否在校验状态 Function(name)

resetFields

重置一组输入控件的值(为 initialValue)与状态,如不传入参数,则重置所有组件

Function([names: string[]])

const { form } = this.props;
form.resetFields();
form.resetFields(['integralSillValue']);
form.resetFields(['goodNo', []]);

setFields

设置一组输入控件的值与错误状态:代码

({ [fieldName]: {value: any, errors: [Error] } }) => void

setFieldsValue

设置一组输入控件的值(注意:不要在 componentWillReceiveProps 内使用,否则会导致死循环,原因( { [fieldName]: value }, callback: Function ) => void

const { getFieldValue, setFieldsValue } = this.props.form;
    const dataSource = getFieldValue('name');
    setFieldsValue({
      name: dataSource,
    });
setFieldsValue({
        'materialConfigDTO.activityName': undefined,
        'materialConfigDTO.activityMode': 0
    })

validateFields

校验并获取一组输入域的值与 Error,若 fieldNames 参数为空,则校验全部组件

(
  [fieldNames: string[]],
  [options: object],
  callback(errors, values)
) => void

errors:

{
  "username": {
    "errors": [
      {
        "message": "Please input your username!",
        "field": "username"
      }
    ]
  },
  "password": {
    "errors": [
      {
        "message": "Please input your Password!",
        "field": "password"
      }
    ]
  }
}

values:

{
  "username": "username",
  "password": "password",
}
this.props.form.validateFields((err, values) => {
    if (!err) {
// ...
    }
})
this.props.form.validateFields(['timesDate', 'applyLevel', 'platformId', 'businessId'], (err, values) => {
      if (!err) {
// ...
    }
})

validateFieldsAndScroll

validateFields 相似,但校验完后,如果校验不通过的菜单域不在可见范围内,则自动滚动进可见范围

参考 validateFields

const {
  form: { validateFields },
} = this.props;
validateFields((errors, values) => {
  // ...
});
validateFields(['field1', 'field2'], (errors, values) => {
  // ...
});
validateFields(['field1', 'field2'], options, (errors, values) => {
  // ...
});

其中options可配置:

options.first

若为 true,则每一表单域的都会在碰到第一个失败了的校验规则后停止校验

options.firstFields

指定表单域会在碰到第一个失败了的校验规则后停止校验

options.force

对已经校验过的表单域,在 validateTrigger 再次被触发时是否再次校验

options.scroll

定义 validateFieldsAndScroll 的滚动行为,详细配置见 dom-scroll-into-view config

Form.Item

colon

配合 label 属性使用,表示是否显示 label 后面的冒号

extra

额外的提示信息,和 help 类似,当需要错误信息和提示文案同时出现时,可以使用这个。

<FormItem label='宣传图片' {...formLayout} extra='支持格式:png、jpg、jpeg不大于1M;推荐图片尺寸:800px*800px'>

hasFeedback

img

help

help={'xxxxxxxxxxxxxxxxxxxx'}

htmlFor

设置子元素 label htmlFor 属性

<List.Item style={{ position: 'relative' }}>
                      <label
                        htmlFor={String(item.id)}
                        style={{
                          display: 'block',
                          width: '100%',
                          height: 100,
                          lineHeight: '100px',
                          textAlign: 'center',
                          color: '#ccc',
                          cursor: item.enable ? 'pointer' : 'not-allowed'
                        }}
                      >
                        {item.picUrl ? (
                          <img
                            style={{ width: '100%', height: '100%' }}
                            alt="奖品"
                            src={item.picUrl}
                          />
                        ) : (
                          '暂无图片'
                        )}
                      </label>
                      <div
                        style={{
                          textAlign: 'center',
                          textOverflow: 'ellipsis',
                          overflow: 'hidden'
                        }}
                      >
                        <Radio disabled={!item.enable} id={String(item.id)} value={item.id}>
                          {item.name}
                        </Radio>
                      </div>
                    </List.Item>

labelCol

wrapperCol

const tailItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
};

labelAlign

required

validateStatus

// 验证模板名称
  validatePrimeName = (value) => {
    if (value != '' && value.length > 1) {
      return {
        validateStatus: 'success',
        errorMsg: null,
      };
    }
    return {
      validateStatus: 'error',
      errorMsg: '请输入模板名称,2-25个字',
    };
  }

validator

自定义校验(注意,callback 必须被调用

function(rule, value, callback)

validatorStores = (storesArrType, msg, rule, value, callback) => {
    const arr = this.state[storesArrType] || [];
    if (value == 2 && arr.length == 0) {
      callback(msg);
    } else {
      callback();
    }
  };

storeRadio = (e, key, valid, msg) => {
    if (e.target.value == 1) {
      this.setState({
        [key]: [],
        [valid + 'ValidateStatus']: '',
        [valid + 'ErrorMsg']: null,
      });
    } else if (e.target.value == 2) {
      this.setState({
        [valid + 'ValidateStatus']: 'error',
        [valid + 'ErrorMsg']: msg,
      });
    }
  }
  
  ...
  
{getFieldDecorator('activateStore.status', {
                initialValue: 1,
                rules: [
                  {
                    validator: this.validatorStores.bind(
                      this,
                      'activateStoreArr',
                      '请选择线上领卡门店'
                    )
                  }
                ]
              })(
                <RadioGroup
                  onChange={e =>
                    this.props.storeRadio(
                      e,
                      'activateStoreArr',
                      'activateStore.status',
                      '请选择线上领卡门店'
                    )
                  }
                >
                  <Radio value={1}>全部门店</Radio>
                  <Radio value={2}>部分门店</Radio>
                </RadioGroup>
              )}

pattern

正则表达式校验

<FormItem label="收货人姓名" {...formItemLayout}>
                      {getFieldDecorator('buyerFullName', {
                        initialValue: orderInfo.buyerFullName || '',
                        rules: [
                          {
                            pattern: /^.{1,20}$/,
                            message: '收货人姓名最多支持20位字符'
                          },
                          {
                            required: true,
                            message: '请填写收货人姓名'
                          }
                        ]
                      })(
                        <Input
                          onChange={this.checkFullNameBlankSpace.bind(this)}
                          placeholder="请填写收货人姓名"
                          onKeyUp={e => {
                            e.target.value = e.target.value.replace(/\s+/g, '');
                          }}
                          disabled={notChange}
                        />
                      )}
                    </FormItem>

whitespace

必选时,空格是否会被视为错误

{ required: true, whitespace: true, message: '请输入页面标题' },

getDefaultProps

object getDefaultProps()

执行过一次后,被创建的类会有缓存,映射的值会存在this.props,前提是这个prop不是父组件指定的
这个方法在对象被创建之前执行,因此不能在方法内调用this.props ,另外,注意任何getDefaultProps()返回的对象在实例中共享,不是复制

getInitialState

object getInitialState()

控件加载之前执行,返回值会被用于state的初始化值

componentWillMount

void componentWillMount()

执行一次,在初始化render之前执行,如果在这个方法内调用setStaterender()知道state发生变化,并且只执行一次

render

ReactElement render()

render的时候会调用render()会被调用
调用render()方法时,首先检查this.propsthis.state返回一个子元素,子元素可以是DOM组件或者其他自定义复合控件的虚拟实现
如果不想渲染可以返回null或者false,这种场景下,React渲染一个<noscript>标签,当返回null或者false时,ReactDOM.findDOMNode(this)返回null
render()方法是很纯净的,这就意味着不要在这个方法里初始化组件的state,每次执行时返回相同的值,不会读写DOM或者与服务器交互,如果必须如服务器交互,在componentDidMount()方法中实现或者其他生命周期的方法中实现,保持render()方法纯净使得服务器更准确,组件更简单

componentDidMount

void componentDidMount()

在初始化render之后只执行一次,在这个方法内,可以访问任何组件,componentDidMount()方法中的子组件在父组件之前执行

从这个函数开始,就可以和 JS 其他框架交互了,例如设置计时 setTimeout 或者 setInterval,或者发起网络请求

shouldComponentUpdate

boolean shouldComponentUpdate(
  object nextProps, object nextState
)

这个方法在初始化render时不会执行,当props或者state发生变化时执行,并且是在render之前,当新的props或者state不需要更新组件时,返回false

shouldComponentUpdate: function(nextProps, nextState) {
  return nextProps.id !== this.props.id;
}

shouldComponentUpdate方法返回false时,讲不会执行render()方法,componentWillUpdatecomponentDidUpdate方法也不会被调用

默认情况下,shouldComponentUpdate方法返回true防止state快速变化时的问题,但是如果·state不变,props只读,可以直接覆盖shouldComponentUpdate用于比较propsstate的变化,决定UI是否更新,当组件比较多时,使用这个方法能有效提高应用性能

componentWillUpdate

void componentWillUpdate(
  object nextProps, object nextState
)

propsstate发生变化时执行,并且在render方法之前执行,当然初始化render时不执行该方法,需要特别注意的是,在这个函数里面,你就不能使用this.setState来修改状态。这个函数调用之后,就会把nextPropsnextState分别设置到this.propsthis.state中。紧接着这个函数,就会调用render()来更新界面了

componentDidUpdate

void componentDidUpdate(
  object prevProps, object prevState
)

组件更新结束之后执行,在初始化render时不执行

componentWillReceiveProps

void componentWillReceiveProps(
  object nextProps
)

props发生变化时执行,初始化render时不执行,在这个回调函数里面,你可以根据属性的变化,通过调用this.setState()来更新你的组件状态,旧的属性还是可以通过this.props来获取,这里调用更新状态是安全的,并不会触发额外的render调用

componentWillReceiveProps: function(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}

componentWillUnmount

void componentWillUnmount()

当组件要被从界面上移除的时候,就会调用componentWillUnmount(),在这个函数中,可以做一些组件相关的清理工作,例如取消计时器、网络请求等

建议只有在componentWillMount,componentDidMount,componentWillReceiveProps方法中可以修改state

Input

addonBefore

带标签的 input,设置前置标签

addonAfter

带标签的 input,设置后置标签

string|ReactNode

defaultValue

输入框默认内容

string

<Input addonBefore="Http://" addonAfter=".com" defaultValue="mysite" />

disabled

是否禁用状态,默认为 false

id输入框的 id

maxLength最大长度

prefix

带有前缀图标的 input

suffix

带有后缀图标的 input

string|ReactNode

<Input
      placeholder="Enter your username"
      prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
      suffix={
        <Tooltip title="Extra information">
          <Icon type="info-circle" style={{ color: 'rgba(0,0,0,.45)' }} />
        </Tooltip>
      }
    />

onChange

输入框内容变化时的回调

onPressEnter

按下回车的回调

allowClear

可以点击清除图标删除内容

Select

labelInValue

是否把每个选项的 label 包装到 value 中,会把 Select 的 value 类型从 string 变为 {key: string, label: ReactNode} 的格式

notFoundContent

当下拉列表为空时显示的内容

showArrow

是否显示下拉小箭头

allowClear

支持清除

autoClearSearchValue

是否在选中项后清空搜索框,只在 modemultipletags 时有效。

autoFocus

默认获取焦点

defaultActiveFirstOption

是否默认高亮第一个选项。

firstActiveValue

默认高亮的选项

string|string[]

dropdownMatchSelectWidth

下拉菜单和选择器同宽

dropdownRender

自定义下拉框内容

onSelect

被选中时调用,参数为选中项的 value (或 key) 值

function(string|number|LabeledValue, option:Option)

onDeselect

取消选中时调用,参数为选中项的 value (或 key) 值,仅在 multiple 或 tags 模式下生效

function(string|number|LabeledValue)

onSearch

文本框值变化时回调

filterOption

是否根据输入项进行筛选。当其为一个函数时,会接收 inputValue option 两个参数,当 option 符合筛选条件时,应返回 true,反之则返回 false

showSearch

使单选模式可搜索

onFocus

获得焦点时回调

onBlur

失去焦点时回调

onChange

选中 option,或 input 的 value 变化(combobox 模式下)时,调用此函数

function(value, option:Option/Array

suffixIcon

自定义的选择框后缀图标

removeIcon

自定义的多选框清除图标

clearIcon

自定义的多选框清空图标

menuItemSelectedIcon

自定义多选时当前选中的条目图标

标签:控件,string,render,value,笔记,props,antd,options
来源: https://www.cnblogs.com/journeyIT/p/16107590.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有