使用Frontity显示文章评论

frontity post comments

本篇文章介绍如何使用 Frontity 的 Comments 组件显示文章的评论。

首先在项目的根目录中安装 Frontity Comments 组件包。

npm i @frontity/wp-comments

第二步在 frontity.settings.js 中配置对该包的引用。


packages: [“@frontity/wp-comments”],

第三步从 WordPress 获取文章的评论。

sample-frontity-project/packages/frontity-chakra-theme/src/components/comments/ index.js

import React, { useEffect } from "react";
import { connect } from "frontity";
import { Box, Heading, Divider } from "@chakra-ui/react";
import CommentsList from "./comments-list";
import CommentsForm from "./comments-form";
import { displayTextString } from "../text-string";

const Comments = ({ actions, state, postId }) => {
  useEffect(() => {
    actions.source.fetch(`@comments/${postId}`);
  }, []); //获取文章的评论
  const data = state.source.get(`@comments/${postId}`);
  return (
    data.isReady && data.items.length>0 && (
    <>
      <Divider borderBottom="1px solid" my="20px" />
      <Box p="5">
        <Heading pb="1" fontSize="x-large" as="h6" textTransform="uppercase">{displayTextString(0, "comments")}</Heading>
        {/*<CommentsForm postId={postId} />*/}
        <CommentsList postId={postId} />  {/*调用显示文章的组件*/}
      </Box>
    </>
    )
  );
};

export default connect(Comments);

第四步显示文章的评论。

sample-frontity-project/packages/frontity-chakra-theme/src/components/comments/ comments-list.js

import React from "react";
import { connect, styled } from "frontity";

const CommentsList = ({ state, libraries, postId }) => {
  const data = state.source.get(`@comments/${postId}`);
  const Html2React = libraries.html2react.Component;
  const renderComments = (items) => 
    items.map(({ id, children }) => (
      <>
        <Comment key={id}>
          <div>
            {state.source.comment[id].author_name || "Anonymous"}:
          </div>
          <CommentContent>
            <Html2React
              html={state.source.comment[id].content.rendered}
            />
          </CommentContent>
          { children && renderComments(children) }  {/*递归显示子评论*/}
        </Comment>
      </>
  ));
  
  return renderComments(data.items);
};

export default connect(CommentsList);

const Container = styled.div`
  margin: 40px;
`;

const Comment = styled.div`
  border: 1px solid black;
  padding: 20px;
`;
const CommentContent = styled.div`
  padding-left: 10px;
`;

最后在文章显示组件的合适位置加入评论显示组件。

sample-frontity-project/packages/frontity-chakra-theme/src/components/post/post.js

...
        {/* 调用文章评论显示组件 */}
        <Comments postId={postData.id}></Comments>
        {/* 调用相关文章显示组件 */}
        <PostRelated postType={postData.type} postId={postData.id} />
...
frontity post comments
Frontity 显示文章评论

发表评论

邮箱地址不会被公开。 必填项已用*标注