【问题标题】:Using react-admin , How to create a comment from a post使用 react-admin ,如何从帖子中创建评论
【发布时间】:2018-12-04 03:57:05
【问题描述】:

我正在为一个新项目使用 react-admin。我有权面临的挑战之一是创建类似 a comment from a post 之类的东西。这是我尝试这样做的方式<CreateButton basePath='/prescriptions' label="prescriptions" record={data}/>。我面临的问题是使用 post form 中的 data record 来创建评论,这意味着我想发送 post_id 使用来自 commentForm 的 其他数据。提前感谢您帮助我。

【问题讨论】:

标签: reactjs admin-on-rest api-platform.com react-admin


【解决方案1】:

嗯,我在comment 中提到的帖子很快就会发布。此外,我们将在2.2.0 中默认支持此功能。同时,您可以执行以下操作:

import { parse } from "query-string";

const CommentCreate = props => {
    // Read the post_id from the location which is injected by React Router and passed to our component by react-admin automatically
    const { post_id: post_id_string } = parse(props.location.search);

    // Optional if you're not using integers as ids
    const post_id = post_id_string ? parseInt(post_id_string, 10) : '';

    return (
        <Create {...props}>
            <SimpleForm
                defaultValue={{ created_at: today, post_id }}
            >
                // ...
            </SimpleForm>
        </Create>
    );
}

这是从现有帖子创建新评论的按钮:

import CardActions from '@material-ui/core/CardActions';
import ChatBubbleIcon from "@material-ui/icons/ChatBubble";
import { Button } from 'react-admin';

const AddNewCommentButton = ({ record }) => (
    <Button
        component={Link}
        to={{
            pathname: '/comments/create',
            search: `?post_id=${record.id}`
        }}
        label="Add a comment"
    >
        <ChatBubbleIcon />
    </Button>
);

最后,我们如何在帖子Show 组件中将它与ReferenceManyField 一起使用(也可以在Edit 中使用):

const PostShow = props => (
    <Show {...props}>
        <TabbedShowLayout>
        ...
            <Tab label="Comments">
                <ReferenceManyField
                    addLabel={false}
                    reference="comments"
                    target="post_id"
                    sort={{ field: "created_at", order: "DESC" }}
                >
                    <Datagrid>
                        <DateField source="created_at" />
                        <TextField source="body" />
                        <EditButton />
                    </Datagrid>
                </ReferenceManyField>
                <AddNewCommentButton />
            </Tab>
        </TabbedShowLayout>
    </Show>
);

您可以在codesandbox 中看到这一点

编辑:发布的帖子https://marmelab.com/blog/2018/07/09/react-admin-tutorials-form-for-related-records.html

【讨论】:

  • 好东西吉尔达斯!一旦 2.2 默认支持此功能,您在此处提供的解决方案是否需要更改?
  • 并非全部,这也取决于您的需求。 Create 将能够从位置状态或搜索初始化其值。但是,例如,我们不支持对 id 的默认整数解析,因此该解决方案在某些情况下仍然适用。
  • 发布后,我在答案中添加了链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-28
相关资源
最近更新 更多