通用评论

index.js 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import React, { Component } from "react";
  2. import PropTypes from "prop-types";
  3. import { IMAGE_SPLIT } from "../../constant";
  4. import Comment from "../../Comment";
  5. class CommentInput extends Component {
  6. constructor(props) {
  7. super(props);
  8. this.state = {};
  9. this.handleSubmit = this.handleSubmit.bind(this);
  10. }
  11. /**
  12. * 提交评论
  13. * @param {object} { text<string>, files<array> } 需要提交的评论的文本和图片
  14. * @param {function} cb 提交成功后的回掉
  15. */
  16. handleSubmit({ text, files }, cb) {
  17. let value = text;
  18. if (files && files.length) {
  19. value += IMAGE_SPLIT;
  20. files.forEach(file => {
  21. value += `${file},`;
  22. });
  23. }
  24. if (value.substr(-1) === ",") {
  25. value = value.slice(0, -1);
  26. }
  27. const { action, commentId, replyId, callback } = this.props;
  28. if (action === "comment") {
  29. this.props.app.sCreateComment(
  30. {
  31. content: value
  32. },
  33. cb
  34. );
  35. } else if (action === "reply") {
  36. this.props.app.sCreateReply(
  37. {
  38. comment_id: commentId,
  39. content: value
  40. },
  41. () => callback && callback()
  42. );
  43. } else if (action === "replyToReply") {
  44. this.props.app.sCreateReply(
  45. {
  46. comment_id: commentId,
  47. content: value,
  48. reply_id: replyId
  49. },
  50. () => callback && callback()
  51. );
  52. }
  53. }
  54. render() {
  55. const childrenWithProps = React.Children.map(this.props.content, child => {
  56. return React.cloneElement(child, {
  57. // 编辑器本身不提交值,但 CommentInput 会提交
  58. // CommentInput 主要是负责评论的业务逻辑,提交评论和回复
  59. // 默认使用 CommentInput 的 onSubmit 来提交评论
  60. // 但也可以使用 Editor 的 props 来覆盖 onSubmit
  61. onSubmit: this.handleSubmit,
  62. ...child.props,
  63. // 如果当前的编辑器不是“评论”,则编辑器高度减小一些
  64. rows:
  65. this.props.action === "comment"
  66. ? child.props.rows
  67. : child.props.rows - 1
  68. });
  69. });
  70. return <div>{childrenWithProps}</div>;
  71. }
  72. }
  73. CommentInput.propTypes = {
  74. // comment 评论
  75. // reply 评论的回复
  76. // replyToReply 回复的回复
  77. action: PropTypes.oneOf(["comment", "reply", "replyToReply"])
  78. };
  79. CommentInput.defaultProps = {
  80. action: "comment"
  81. };
  82. export default Comment(CommentInput);