Guest User

Untitled

a guest
Oct 20th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. import * as React from 'react'
  2. import CommentInput from './CommentInput'
  3. import CommentList from './CommentList'
  4.  
  5. import './App.css'
  6.  
  7. interface IState {
  8. comments: Array<any>;
  9. }
  10.  
  11. class App extends React.Component<{}, IState> {
  12. public state: IState = {
  13. comments: []
  14. }
  15.  
  16. componentWillMount() {
  17. let data: any = localStorage.getItem('comments')
  18. this.setState({comments: JSON.parse(data)})
  19. }
  20.  
  21. private saveData = (data: any) => {
  22. localStorage.setItem('comments', JSON.stringify(data))
  23. }
  24.  
  25. private handleSubmitComment = (comment: any) => {
  26. if (!comment) return
  27. if (!comment.username) return alert('请输入用户名')
  28. if (!comment.content) return alert('请输入评论内容')
  29.  
  30. const {comments} = this.state
  31. comments.push(comment)
  32. this.setState({comments})
  33.  
  34. this.saveData(comments)
  35. }
  36.  
  37. private handleDeleteComment = (index: number) => {
  38. let {comments} = this.state
  39. comments.splice(index, 1)
  40. this.setState({comments})
  41.  
  42. this.saveData(comments)
  43. }
  44.  
  45. render() {
  46. return (
  47. <div className="wrapper">
  48. <CommentInput onSubmit={this.handleSubmitComment}/>
  49. <CommentList
  50. onDeleteComment={this.handleDeleteComment}
  51. comments={this.state.comments}
  52. />
  53. </div>
  54. )
  55. }
  56. }
  57.  
  58. export default App;
Add Comment
Please, Sign In to add comment