How do you conditionally show fields in “Show” component in react-admin?

杀马特。学长 韩版系。学妹 提交于 2020-03-19 08:06:28

问题


Some fields I want to only show if they have a value. I would expect to do this like so:

<Show {...props} >
  <SimpleShowLayout>
    { props.record.id ? <TextField source="id" />: null }
  </SimpleShowLayout>
</Show>

But that doesn't work. I can make it somewhat work by making each field a higher order component, but I wanted to do something cleaner. Here's the HOC method I have:

const exists = WrappedComponent => props => props.record[props.source] ?
  <WrappedComponent {...props} />: null;

const ExistsTextField = exists(TextField);

// then in the component:

<Show {...props} >
  <SimpleShowLayout>
    <ExistsTextField source="id" />
  </SimpleShowLayout>
</Show>

This correctly shows the value, but strips the label.


回答1:


We need to update our documentation about this. In the mean time, you can find informations about how to achieve that in the upgrade guide: https://github.com/marmelab/react-admin/blob/master/UPGRADE.md#aor-dependent-input-was-removed

Here's an example:

import { ShowController, ShowView, SimpleShowLayout, TextField } from 'react-admin';

const UserShow = props => (
    <ShowController {...props}>
        {controllerProps => 
            <ShowView {...props} {...controllerProps}>
                <SimpleShowLayout>
                    <TextField source="username" />
                    {controllerProps.record && controllerProps.record.hasEmail && 
                        <TextField source="email" />
                    }
                </SimpleShowLayout>
            </ShowView>
        }
    </ShowController>
);


来源:https://stackoverflow.com/questions/50992548/how-do-you-conditionally-show-fields-in-show-component-in-react-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!