react-發表評論案例

評論列表組件

import React from 'react'
import CMTItem from './CmtItem.jsx'
import CMTBox from './CmtBox.jsx'

// 評論列表組件
export default class CMTList extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      list: [
        { user: 'zs', content: '123' },
        { user: 'ls', content: 'qqq' },
        { user: 'xiaohong', content: 'www' }
      ]
    }
  }

  // 在組件還沒有渲染的時候,就當即 獲取數據
  componentWillMount() {
    this.loadCmts()
  }

  render() {
    return <div>
      <h1>這是評論列表組件</h1>

      {/* 發表評論的組件 */}
      {/* 相對於 Vue 中,把 父組件傳遞給子組件的 普通屬性 和 方法屬性,區別對待, 普通屬性用 props 接收, 方法 使用 this.$emit('方法名') */}
      {/* react 中,只要是傳遞給 子組件的數據,無論是 普通的類型,仍是方法,均可以使用 this.props 來調用 */}
      <CMTBox reload={this.loadCmts}></CMTBox>

      <hr />


      {/* 循環渲染一些評論內容組件 */}
      {this.state.list.map((item, i) => {
        return <CMTItem key={i} {...item}></CMTItem>
      })}
    </div>
  }

  // 從本地存儲中加載 評論列表
  loadCmts = () => {
    var list = JSON.parse(localStorage.getItem('cmts') || '[]')
    this.setState({
      list
    })
  }
}

評論顯示

import React from 'react'

// 評論列表項組件
export default class CMTItem extends React.Component {

  render() {
    return <div style={{ border: '1px solid #ccc', margin: '10px 0' }}>
      <h3>評論人:{this.props.user}</h3>
      <h5>評論內容:{this.props.content}</h5>
    </div>
  }
}

發表評論

import React from 'react'

// 評論列表框組件
export default class CMTBox extends React.Component {

  render() {
    return <div>
      <label>評論人:</label><br />
      <input type="text" ref="user" /><br />
      <label>評論內容:</label><br />
      <textarea cols="30" rows="4" ref="content"></textarea><br />

      <input type="button" value="發表評論" onClick={this.postComment} />
    </div>
  }

  postComment = () => {
    // 1. 獲取到評論人和評論內容
    // 2. 從 本地存儲中,先獲取以前的評論數組
    // 3. 把 最新的這條評論,unshift 進去
    // 4. 在把最新的評論數組,保存到 本地存儲中
    var cmtInfo = { user: this.refs.user.value, content: this.refs.content.value }
    var list = JSON.parse(localStorage.getItem('cmts') || '[]')
    list.unshift(cmtInfo)
    localStorage.setItem('cmts', JSON.stringify(list))

    this.refs.user.value = this.refs.content.value = ''

    this.props.reload()
  }
}
相關文章
相關標籤/搜索