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 

这是评论列表组件

{/* 发表评论的组件 */} {/* 相对于 Vue 中,把 父组件传递给子组件的 普通属性 和 方法属性,区别对待, 普通属性用 props 接收, 方法 使用 this.$emit('方法名') */} {/* react 中,只要是传递给 子组件的数据,不管是 普通的类型,还是方法,都可以使用 this.props 来调用 */}
{/* 循环渲染一些评论内容组件 */} {this.state.list.map((item, i) => { return })}
} // 从本地存储中加载 评论列表 loadCmts = () => { var list = JSON.parse(localStorage.getItem('cmts') || '[]') this.setState({ list }) } }

评论显示

import React from 'react'

// 评论列表项组件
export default class CMTItem extends React.Component {

  render() {
    return 

评论人:{this.props.user}

评论内容:{this.props.content}
} }

发表评论

import React from 'react'

// 评论列表框组件
export default class CMTBox extends React.Component {

  render() {
    return 




} 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() } }

你可能感兴趣的:(react-发表评论案例)