通用评论

index.js 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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, userId, 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. business_user_id: userId
  41. },
  42. () => callback && callback()
  43. );
  44. } else if (action === "replyToReply") {
  45. this.props.app.sCreateReply(
  46. {
  47. comment_id: commentId,
  48. content: value,
  49. reply_id: replyId,
  50. business_user_id: userId
  51. },
  52. () => callback && callback()
  53. );
  54. }
  55. }
  56. render() {
  57. const childrenWithProps = React.Children.map(this.props.content, child => {
  58. return React.cloneElement(child, {
  59. // 编辑器本身不提交值,但 CommentInput 会提交
  60. // CommentInput 主要是负责评论的业务逻辑,提交评论和回复
  61. // 默认使用 CommentInput 的 onSubmit 来提交评论
  62. // 但也可以使用 Editor 的 props 来覆盖 onSubmit
  63. onSubmit: this.handleSubmit,
  64. ...child.props,
  65. // 如果当前的编辑器不是“评论”,则编辑器高度减小一些
  66. rows:
  67. this.props.action === "comment"
  68. ? child.props.rows
  69. : child.props.rows - 1
  70. });
  71. });
  72. return <div>{childrenWithProps}</div>;
  73. }
  74. }
  75. CommentInput.propTypes = {
  76. // comment 评论
  77. // reply 评论的回复
  78. // replyToReply 回复的回复
  79. action: PropTypes.oneOf(["comment", "reply", "replyToReply"])
  80. };
  81. CommentInput.defaultProps = {
  82. action: "comment"
  83. };
  84. export default Comment(CommentInput);