除了直接在渲染逻辑中使用 form.getFieldValue 和 useWatch 之外,Ant Design Form 还提供了shouldUpdate属性在 Form.Item 组件上,这是另一种实现表单项之间联动的方式。shouldUpdate 允许你根据其他字段的变化来重新渲染 Form.Item,而不需要直接操作表单状态或使用额外的状态管理。这种方法更适合于当你需要根据一个或多个表单项的值变化来改变当前表单项的行为时使用。
使用 shouldUpdate 实现表单项联动
下面是一个使用shouldUpdate 的例子,它展示了如何根据一个单选按钮的选择来显示一个额外的输入框:
import React from 'react';import { Form, Input, Radio, Button } from 'antd';const FormItemDependencyWithShouldUpdate = () => {return (<Form layout="vertical"><Form.Item name="choice" label="选择"><Radio.Group><Radio value="option1">选项1</Radio><Radio value="option2">选项2</Radio></Radio.Group></Form.Item>{/* 使用shouldUpdate监听choice字段的变化 */}<Form.Item shouldUpdate={(prevValues, currentValues) => prevValues.choice !== currentValues.choice}>{({ getFieldValue }) => {return getFieldValue('choice') === 'option2' ? (<Form.Itemname="inpu
使用了 listType="picture-card" 后, 删除/上传图片父元素 .ant-upload-list-picture-card 下面会同时存在两个元素, 一个为上传触发元素, 另一个为显示图片的元素
父元素设置 overflow: hidden 来隐藏多余的元素
.ant-upload-list-picture-card {overflow: hidden;height: 300px; // 自行设置合适的高度.ant-upload-select, .ant-upload-list-item-container {width: 100% !important;height: 100% !important;}}
1.循环遍历出最深层子节点,存放在一个数组中
2.将后台返回的含有父节点的数组和第一步骤遍历的数组做比较
3.如果有相同值,将相同值取出来,push到一个新数组中
4.利用这个新的重组的数组给Tree组件selected赋值
const deepArr = [] //deepArr存放所有子节点的数组//第一步骤:子节点放在一个数组中const requestList = (data) => {data && data.map(item => {if (item.children && item.children.length > 0) {requestList(item.children)} else {deepArr.push(item.id)}return null})return deepArr}//第2,3步骤的方法const uniqueTree = (uniqueArr, Arr) => {let uniqueChild = []for (var i in Arr) {for (var k in uniqueArr) {if (uniqueArr[k] === Arr[i]) {uniqueChild.push(uniqueArr[k])}}}return uniqueChild}//调用第2,3步骤的方法const getRoleInfo = () => {getData({ id: Id }).then(res => {const ids = res.dataconst uniqueChild = this.uniqueTree(ids, deepArr)setCheckedKeys(uniqueChild)})}<TreecheckablecheckedKeys={checkedKeys}defaultExpandedKeys={checkedKeys}fieldNames={{
disabledDate = (current) => {return current && current < moment().startOf('day').subtract(0, 'days');}
disabledRangeTime = (_, type) => {const { form: { getFieldValue } } = this.propsif (type === 'start') {const nowHours = moment().hours()const time = getFieldValue("time")if (time && moment(time[0].format("YYYY-MM-DD")).valueOf() <= moment(moment().format("YYYY-MM-DD")).valueOf()) {return {disabledHours: () => this.range(0, nowHours),};}}}
onOpenChange = (status) => {const { form: { getFieldValue, setFields } } = this.propsconst time = getFieldValue("time")if (!status) {if (time && (moment(time[0]).valueOf() + 10000) < moment().valueOf()) {setFields({time: {value: null,errors: [n