react学习五:升级评论列表案例

CmtList.jsx:

评论列表组件

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: '', content: '' }
      ]
    }
  }

  // 在组件尚未渲染的时候,就立即 获取数据
  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
    })
  }
}

CmtBox.jsx:

评论列表框组件

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

CmtItem.jsx:

评论列表项组件

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

效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值