利用React实现评论功能

React功能之网页评论

效果如图所示
在这里插入图片描述

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component{
  state = {
    comments:[
      {id:1, name:"jack", content:"你好"},
      {id:2, name:"rose", content:"板凳"},
      {id:3, name:"tom", content:"楼主好人"}
    ],
    userName:'',
    userContent:''
  }
  rednderList(){
    const {comments} = this.state
    if(comments.length ===0){
      return <div className='no-conmment'>暂无评论,快去评论吧</div>
    }
    return(
      <ul>
           {
            comments.map(item=>(
              <li key={item.id}>
                 <h3 >用户:{item.name}</h3>
                 <p>评论内容:{item.content}</p>
              </li>
            ))
          }
         </ul>
    )
  }
  
  handleForm = (e)=>{
    const {name, value} = e.target;
    this.setState({
      [name]:value
    })
  }
  
  addConment= ()=>{
    const {comments,userName, userContent} = this.state;
    if(userName.trim()===''||userContent.trim()===''){
      alert('请输入昵称和内容');
      return;
    }
    const newComments = [{
      id: Math.random(),
      name:userName,
      content:userContent
    },...comments]
    this.setState({
      comments:newComments,
      userName:'',
      userContent:''
    })


  }

  render(){
    const {userName, userContent} = this.state;

    return(
      <div className='app'>
        <input className='user' type="text" placeholder='请输入昵称' value={userName} name="userName" onChange={this.handleForm}></input>
        <br />
        <textarea
          className='content'
          cols="30"
          rows="10"
          placeholder='请输入评论内容'
          value={userContent}
          name="userContent"
          onChange={this.handleForm}
        ></textarea>
        <br />
        <button onClick={this.addConment}>发表评论</button>
        {this.rednderList()}
      </div>
    )
  }
}
ReactDOM.render(<App />, document.getElementById('root'))
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值