react初体验

2019-02-27  本文已影响0人  Biger丶
import React, { Component } from "react";

class App extends Component {
 constructor() {
   super();
   this.state = {
     list: [
       { id: 1, user: "Biger1", content: "learn react" },
       { id: 2, user: "Biger2", content: "learn redux" }
     ],
     iptUser: "",
     iptContent: ""
   };
 }

 // 添加留言
 addmsg() {
   const { list, iptUser, iptContent } = this.state;
   if (!iptUser || !iptContent) {
     return;
   }
   const arr = [...list];
   arr.push({
     id: arr.length ? arr[arr.length - 1].id + 1 : 0,
     user: iptUser,
     content: iptContent
   });
   this.setState({
     list: arr,
     iptUser: "",
     iptContent: ""
   });
 }

 // 删除留言
 delmsg(val) {
   const { list } = this.state;
   const arr = list.filter(v => {
     return v.id !== val.id;
   });
   this.setState({
     list: arr
   });
 }

 // 控制用户输入
 handleInput(ev) {
   this.setState({
     [ev.target.name]: ev.target.value
   });
 }
 // 界面渲染
 render() {
   const { list, iptUser, iptContent } = this.state;
   return (
     <div>
       <h4>留言列表</h4>
       <input
         type="text"
         placeholder="用户"
         value={iptUser}
         name="iptUser"
         onChange={this.handleInput.bind(this)}
       />
       <br />
       <input
         type="text"
         placeholder="留言"
         value={iptContent}
         name="iptContent"
         onChange={ev => {
           this.handleInput(ev);
         }}
       />
       <br />
       <button onClick={this.addmsg.bind(this)}>添加</button>
       <ul>
         {list.map(val => {
           return (
             <div key={val.id}>
               <li>
                 {val.user}:{val.content}
               </li>
               <button onClick={this.delmsg.bind(this, val)}>删除</button>
             </div>
           );
         })}
       </ul>
     </div>
   );
 }
}

export default App;
上一篇下一篇

猜你喜欢

热点阅读