current position:Home>Using react to realize comment function

Using react to realize comment function

2022-04-29 04:54:11Orange juice I

React Functional web comments

The effect is shown in the figure
 Insert picture description here

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

class App extends React.Component{
    
  state = {
    
    comments:[
      {
    id:1, name:"jack", content:" Hello "},
      {
    id:2, name:"rose", content:" Bench "},
      {
    id:3, name:"tom", content:" Good man "}
    ],
    userName:'',
    userContent:''
  }
  rednderList(){
    
    const {
    comments} = this.state
    if(comments.length ===0){
    
      return <div className='no-conmment'> No comments , Go and comment </div>
    }
    return(
      <ul>
           {
    
            comments.map(item=>(
              <li key={
    item.id}>
                 <h3 > user :{
    item.name}</h3>
                 <p> Comment content :{
    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(' Please enter your nickname and content ');
      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=' Please enter your nickname ' value={
    userName} name="userName" onChange={
    this.handleForm}></input>
        <br />
        <textarea
          className='content'
          cols="30"
          rows="10"
          placeholder=' Please enter comments '
          value={
    userContent}
          name="userContent"
          onChange={
    this.handleForm}
        ></textarea>
        <br />
        <button onClick={
    this.addConment}> Comment </button>
        {
    this.rednderList()}
      </div>
    )
  }
}
ReactDOM.render(<App />, document.getElementById('root'))

copyright notice
author[Orange juice I],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/116/202204261127530370.html

Random recommended