1

我正在将 react-admin 用于一个新项目。我有权面临的挑战之一是从帖子中创建类似评论的内容。这是我尝试做的方式<CreateButton basePath='/prescriptions' label="prescriptions" record={data}/>。我面临的问题是使用post 表单中的数据记录来创建评论,这意味着我想将post_id与commentForm 中的其他数据一起发送。提前感谢您帮助我。

4

1 回答 1

2

好吧,我在此评论中提到的帖子将很快发布。此外,我们将在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>
);

最后,我们如何ReferenceManyField在 postShow组件中使用它(也可以使用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>
);

您可以在此代码框中看到这一点

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

于 2018-07-06T09:58:24.607 回答