admin-on-rest中ShowButton自定义路径实现方案咨询
当然可以实现!针对你这种在ReferenceManyField下根据不同collectionable_type(Collection或LearningObject)跳转到对应Show页面的需求,我们可以通过自定义ShowButton组件来动态生成跳转路径,下面是具体的实现步骤和示例:
1. 创建自定义ShowButton组件
我们需要封装一个自定义按钮,根据当前记录的collectionable_type值,决定跳转的目标URL。这里有两种实现方式,你可以根据自己的习惯选择:
方式一:通过修改resource属性
利用React Admin原生ShowButton的resource属性,自动生成对应资源的Show页面路径:
import { ShowButton, useRecordContext } from 'react-admin'; const CustomShowButton = (props) => { const record = useRecordContext(); if (!record) return null; // 根据collectionable_type映射对应的资源名称 const resourceMap = { Collection: 'collections', LearningObject: 'learning-objects' }; const targetResource = resourceMap[record.collectionable_type] || props.resource; return <ShowButton {...props} resource={targetResource} />; };
方式二:直接指定to属性
如果需要更灵活的路径控制,可以直接给ShowButton传递to属性,手动定义跳转URL:
import { ShowButton, useRecordContext } from 'react-admin'; const CustomShowButton = (props) => { const record = useRecordContext(); if (!record) return null; // 根据类型生成目标路径 const targetPath = record.collectionable_type === 'Collection' ? `/collections/${record.id}` : `/learning-objects/${record.id}`; return <ShowButton {...props} to={targetPath} />; };
2. 在ReferenceManyField中使用自定义按钮
接下来,在你的CollectionShow组件里,把默认的ShowButton替换成我们刚创建的CustomShowButton即可:
import { Show, ReferenceManyField, Datagrid, TextField } from 'react-admin'; import CustomShowButton from './CustomShowButton'; // 引入自定义组件 const CollectionShow = () => ( <Show> {/* 其他展示字段 */} <ReferenceManyField reference="collectionables" // 你的关联资源名称 target="collection_id" // 关联外键字段 > <Datagrid> <TextField source="collectionable_type" /> <TextField source="name" /> {/* 其他需要展示的字段 */} <CustomShowButton /> {/* 使用自定义按钮 */} </Datagrid> </ReferenceManyField> </Show> ); export default CollectionShow;
注意事项
- 确保你的React Admin应用已经配置了对应资源的Show路由,比如:
// 在App.js或路由配置文件中 import { Admin, Resource } from 'react-admin'; import CollectionShow from './CollectionShow'; import LearningObjectShow from './LearningObjectShow'; const App = () => ( <Admin dataProvider={dataProvider}> <Resource name="collections" show={CollectionShow} /> <Resource name="learning-objects" show={LearningObjectShow} /> {/* 其他资源配置 */} </Admin> ); - 如果
collectionable_type的取值和资源名称不一致,一定要在resourceMap里做好正确的映射,避免路径错误。
内容的提问来源于stack exchange,提问作者Clarissa D. Pereira
相关产品推荐
相关产品推荐

