tutorial.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. let Comment = React.createClass({
  2. rawMarkup: function () {
  3. let rawMarkup = marked(this.props.children.toString(), { sanitize: true });
  4. return { __html: rawMarkup };
  5. },
  6. render: function () {
  7. return (
  8. <div className="comment">
  9. <h2 className="commentAuthor">
  10. {this.props.author}
  11. </h2>
  12. <span dangerouslySetInnerHTML={this.rawMarkup()} />
  13. </div>
  14. );
  15. }
  16. });
  17. let CommentList = React.createClass({
  18. render: function () {
  19. let commentNodes = this.props.data.map(function (comment) {
  20. return (
  21. <Comment author={comment.author} key={comment.id}>
  22. {comment.text}
  23. </Comment>
  24. );
  25. });
  26. return (
  27. <div className="commentList">
  28. {commentNodes}
  29. </div>
  30. );
  31. }
  32. });
  33. let CommentForm = React.createClass({
  34. render: function () {
  35. return (
  36. <div className="commentForm">
  37. <form className="commentForm">
  38. <input type="text" placeholder="Your name" />
  39. <input type="text" placeholder="Say something..." />
  40. <input type="submit" value="Post" />
  41. </form>
  42. </div>
  43. );
  44. }
  45. });
  46. let CommentBox = React.createClass({
  47. componentDidMount: function () {
  48. this.loadCommentsFromServer();
  49. setInterval(this.loadCommentsFromServer, this.props.pollInterval);
  50. },
  51. getInitialState: function () {
  52. return { data: [] };
  53. },
  54. loadCommentsFromServer: function () {
  55. $.ajax({
  56. url: this.props.url,
  57. dataType: "json",
  58. cache: false,
  59. success: function (result) {
  60. this.setState({ data: result });
  61. }.bind(this),
  62. error: function (xhr, status, err) {
  63. console.error(this.props.url, status, err.toString());
  64. }.bind(this)
  65. });
  66. },
  67. render: function () {
  68. return (
  69. <div className="commentBox">
  70. <h1>Comments</h1>
  71. <CommentList data={this.state.data} />
  72. <CommentForm />
  73. </div>
  74. );
  75. }
  76. });
  77. ReactDOM.render(
  78. <CommentBox url="/api/comments" pollInterval={2000} />,
  79. document.getElementById("content")
  80. );