react简单版评论案例

138 阅读1分钟

index.js内容



import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';


class App extends React.Component {
  state = {
    comments: [
      { id: 1, name: 'jack', content: '沙发!!!' },
      { id: 2, name: 'rose', content: '板凳~' },
      { id: 3, name: 'tom', content: '楼主好人' },
    ],
    userName: '',
    userContent: '',
  };
  // 模板 判断是否有内容
  renderList() {
    const { comments } = this.state;
    if (comments.length === 0) {
      return <div className="no-comment">暂无评论,快去评论吧~</div>;
    }
    return (
      <ul>
        {comments.map((item) => (
          <li key={item.id}>
            <h3>评论人:{item.name}</h3>
            <p>评论内容:{item.content}</p>
          </li>
        ))}
      </ul>
    );
  }
  // 获取表单数据 注意 name和value要保持一致
  handleForm = (e) => {
    const { name, value } = e.target;
    this.setState({
      [name]: value,
    });
  };
  // 发表评论 从头部添加 并清空内容
  addComments = () => {
    const { comments, userName, userContent } = this.state;
    if (userContent.trim() === '' || userName.trim() === '') {
      alert('请输入内容');
      return;
    }
    // ES6的新语法
    const newCommentList = [
      {
        id: Math.random(),
        name: userName,
        content: userContent,
      },
      ...comments,
    ];
    this.setState({
      comments: newCommentList,
      userName: '',
      userContent: '',
    });
  };
  render() {
    const { userContent, userName } = this.state;

    return (
      <div className="app">
        <div>
          <input
            className="user"
            type="text"
            placeholder="请输入评论人"
            value={userName}
            name="userName"
            onChange={this.handleForm}
          />
          <br />
          <textarea
            className="content"
            cols="30"
            rows="10"
            placeholder="请输入评论内容"
            value={userContent}
            name="userContent"
            onChange={this.handleForm}
          />
          <br />
          <button onClick={this.addComments}>发表评论</button>
          {this.renderList()}
        </div>
      </div>
    );
  }
}

// 渲染组件
ReactDOM.render(<App />, document.getElementById('root'));

index.css内容

body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }

code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; }

.app { width: 300px; padding: 10px; border: 1px solid #999; }

.user { width: 100%; box-sizing: border-box; margin-bottom: 10px; }

.content { width: 100%; box-sizing: border-box; margin-bottom: 10px; }

.no-comment { text-align: center; margin-top: 30px; }