React创建索引表单:根据Type值(11/14)条件显示RefId字段
调整后的React表单代码
以下是满足需求的修改后代码:
import React from 'react'; import FormElement from '../../../../common/form-element'; import { IFormProps } from '../../../../../interfaces/form-props'; import { Col, Row } from 'antd'; import Index from '../../../../../api/nuclearMedicineApi/services/Index'; import { useQuery } from 'react-query'; import { useIntl } from 'react-intl'; interface IndexFormProps extends IFormProps { } const IndexForm: React.FC<IndexFormProps> = ({ control, disabled, type, data }) => { // 获取所有索引类型 const getAllIndexTypesQuery = useQuery('getAllIndexTypes', () => Index.indexGetAllTypes(), ); // 根据选中的type获取RefId选项,添加type值作为依赖项,确保类型变化时重新请求 const getIndexGetAllLite = useQuery( ['getIndexGetAllLite', data?.type?.value], () => Index.indexGetAllLite({ Type: data?.type?.value}), { enabled: !!data?.type?.value } // 只有当type值存在时才触发查询 ); const sharedProps = { control, disabled, }; const { formatMessage } = useIntl(); return ( <div className='permissions p-8'> <Row> <Col span={24}> <FormElement {...sharedProps} label={'indexName'} type='input' name={'name'} required /> </Col> <Col span={24}> <FormElement {...sharedProps} label={'indexType'} type='select' name={'type'} options={ getAllIndexTypesQuery.data?.map((op) => ({ ...op, label: formatMessage({ id: op?.label }), })) } required /> </Col> {/* 当处于创建模式且type值为11或14时,显示RefId字段 */} {type === 'Create' && (data?.type?.value === 11 || data?.type?.value === 14) && ( <Col span={24}> <FormElement {...sharedProps} label={'refId'} type='select' name={'refId'} options={ getIndexGetAllLite.data?.items?.map((op) => ({ ...op, label: formatMessage({ id: op.label }), })) } required /> </Col> )} {type !== 'Create' && ( <> <Col span={24} className="m-8"> <FormElement {...sharedProps} label={'isActive'} type='checkbox' name='isActive' disabled /> </Col> </> )} </Row> </div> ); }; export default IndexForm;
关键修改说明
- 修正显示条件:将原代码中判断type值为13/14的逻辑改为11/14,同时调整括号位置确保逻辑优先级正确——只有在创建模式(
type === 'Create')下,且选中的type值为11或14时,才显示RefId字段。 - 优化查询触发逻辑:给
getIndexGetAllLite的useQuery添加了查询键依赖项['getIndexGetAllLite', data?.type?.value],并设置enabled: !!data?.type?.value,确保只有当type值存在时才发起请求,且type值变化时自动重新获取对应的RefId选项数据。 - 简化条件判断写法:将三元表达式改为逻辑与(
&&)写法,代码更简洁易读。
内容的提问来源于stack exchange,提问作者Hiba Youssef
相关产品推荐
相关产品推荐

