React implements simple comment publishing function

Knowledge points:

  1. Creation and rendering of class components

  1. conditional rendering

  1. List rendering: using map

  1. destructuring assignment

  1. input, textarea controlled components

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

class App extends React.Component{
    state={
        txt:'',
        content:'',
        commit:[
            {id:1,name:'wuhu',content:'hhh'},
            {id:2,name:'yoho',content:'xxx'}
        ],

    }
    // 条件渲染
    commitBoard=()=>{
        // /解构赋值
        // const {commit}=this.state
        // 条件渲染
        if(this.state.commit.length){
            // 列表渲染
            return (
                <ul>
                    {
                        this.state.commit.map(item=>
                            (<li key={item.id}>
                                <h2>评论人:{item.name}</h2>
                                <p>评论:{item.content}</p>
                            </li>)
                         )  
                    }
                </ul>
                
            )
        }
        return (
            <div>暂无数据</div>
        )
    }
    // 箭头函数解决this指向问题
    handleChange=(e)=>{
        const {name,value}=e.target
        this.setState({
            [name]:value
        })
        
    }
    handleClick=()=>{
        const {txt,content,commit}=this.state
        let commits=commit
        if(this.state.txt)
            commits.push({id:Math.random(),name:txt,content:content})
        else
            alert('请输入内容')
        this.setState({
            commit:commits,
            txt:'',
            content:''
        })
    }
    render(){
        const {txt,content}=this.state
        return(
            <div>
                <div>
                    <input type="text" name="txt" value={txt} onChange={this.handleChange}></input>
                </div>
                <div>
                    <textarea name="content" value={content} onChange={this.handleChange}></textarea>
                </div>
                <div>
                    <button onClick={this.handleClick}>发表评论</button>
                </div>
                <div>{this.commitBoard()}</div>
            </div>
        )
    }
}

ReactDOM.render(<App />,document.getElementById('root'))

Guess you like

Origin blog.csdn.net/sxp19980829/article/details/128666205