zoukankan      html  css  js  c++  java
  • 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()
      }
    }
    
  • 相关阅读:
    UVA 408 (13.07.28)
    linux概念之用户,组及权限
    Java实现 蓝桥杯 历届试题 网络寻路
    Java实现 蓝桥杯 历届试题 约数倍数选卡片
    Java实现 蓝桥杯 历届试题 约数倍数选卡片
    Java实现 蓝桥杯 历届试题 约数倍数选卡片
    Java实现 蓝桥杯 历届试题 约数倍数选卡片
    Java实现 蓝桥杯 历届试题 约数倍数选卡片
    Java实现 蓝桥杯 历届试题 九宫重排
    Java实现 蓝桥杯 历届试题 九宫重排
  • 原文地址:https://www.cnblogs.com/treeskyer/p/13494323.html
Copyright © 2011-2022 走看看