React Admin中如何根据条件禁用数组输入的添加按钮
问题描述
我有一个包含JSON数组字段的对象:
{ "name": "test", "field": [ {"name": "field1","value": "value1"}, {"name": "field2","value": "value2"} ] }
我使用API Platform作为数据提供者,同时用React Admin的EditGuesser写了以下代码:
const SetsEdit = (props:any) => ( <EditGuesser {...props}> <InputGuesser source="name" /> <ArrayInput source="field"> <SimpleFormIterator inline disableAdd={disableAdd(props)}> <TextInput source="name" helperText={false} /> <TextInput source="value" helperText={false} /> </SimpleFormIterator> </ArrayInput> </EditGuesser> );
并在Hydra Admin中使用这个EditGuesser:
<HydraAdmin dataProvider={dataProvider(setRedirectToLogin)} layout={MyLayout} loginPage={LoginPage}> <ResourceGuesser name="sets" edit={SetsEdit} /> </HydraAdmin>
我想实现的是:当field数组长度≥4时,禁用添加按钮。需要给disableAdd属性添加基于对象值的条件判断,请问怎么传递对象值给函数来返回true或false?
解决方案
你可以通过两种方式获取当前编辑的对象数据,进而实现disableAdd的条件判断:
方法一:直接从组件props中提取记录
EditGuesser会把当前编辑的record对象传入组件props,直接读取这个值即可编写判断逻辑:
const SetsEdit = (props: any) => { // 获取当前编辑的记录,做空值避免初始化时报错 const currentRecord = props.record; // 定义禁用逻辑:当field数组长度≥4时返回true const shouldDisableAdd = currentRecord?.field?.length >= 4; return ( <EditGuesser {...props}> <InputGuesser source="name" /> <ArrayInput source="field"> <SimpleFormIterator inline disableAdd={shouldDisableAdd}> <TextInput source="name" helperText={false} /> <TextInput source="value" helperText={false} /> </SimpleFormIterator> </ArrayInput> </EditGuesser> ); };
方法二:使用React Admin的useRecordContext钩子
如果需要在更深层级的组件中获取记录,可以用useRecordContext钩子直接读取当前上下文里的记录:
import { useRecordContext } from 'react-admin'; const SetsEdit = (props: any) => { return ( <EditGuesser {...props}> <InputGuesser source="name" /> <ArrayInput source="field"> <CustomFormIterator /> </ArrayInput> </EditGuesser> ); }; // 自定义迭代器组件,内部获取记录并判断禁用状态 const CustomFormIterator = () => { const record = useRecordContext(); const shouldDisableAdd = record?.field?.length >= 4; return ( <SimpleFormIterator inline disableAdd={shouldDisableAdd}> <TextInput source="name" helperText={false} /> <TextInput source="value" helperText={false} /> </SimpleFormIterator> ); };
关键注意点
- 必须添加空值判断(
record?.field?.length),因为组件初始化时record可能还未加载完成,直接读取会导致报错。 - 当
field数组的内容或长度变化时,React Admin会自动触发组件重新渲染,disableAdd的状态会实时更新。
内容的提问来源于stack exchange,提问作者Girl Codes
相关产品推荐
相关产品推荐

