1. 程式人生 > >React---簡單實現表單點擊提交插入、刪除操作

React---簡單實現表單點擊提交插入、刪除操作

bin submit 實現 pos def stl render extend delet

 1 import React,{Component,Fragment} from ‘react‘
 2 
 3 class App extends Component {
 4   constructor(){
 5     super()  // 要想使用this必須使用super
 6     this.state = {
 7       postList:[
 8         ‘item1‘,
 9         ‘item2‘,
10         ‘item3‘
11       ],
12       inputValue:"test"
13     }
14   }
15
render(){ 16 // jsx語法 17 return ( 18 <Fragment> 19 <ul> 20 { 21 this.state.postList.map((value,index)=>{ 22 return ( 23 <li key={index}>{ value } 24 <button onClick={this
.delete.bind(this,index)}>刪除</button> 25 </li> 26 ) 27 }) 28 } 29 </ul> 30 <div> {this.state.inputValue} </div> 31 <div> 32 <textarea 33 value={ this
.state.inputValue } 34 onChange={ this.handleInput.bind(this) } 35 name="" id=""> 36 </textarea> <br/> 37 <button onClick={ this.submit.bind(this) }>發布</button> 38 </div> 39 </Fragment> 40 ) 41 } 42 submit(){ 43 console.log(0) 44 this.setState({ 45 // postList:this.state.postList.push(e.target.value) 錯誤的,改變了postList原來的值,且要用this.setState設置postList 46 postList:[...this.state.postList,this.state.inputValue], 47 inputValue:"" 48 }) 49 } 50 handleInput(e){ 51 // this.state.inputValue = e.target.value 錯誤的,不能直接賦值 52 // 需要bind(this)改變this指向,讓this指向這個實例 53 this.setState({ 54 inputValue:e.target.value, 55 }) 56 } 57 delete(index){ 58 // 刪除操作需要保留一個副本,在副本上進行操作,該postList是局部的postList,不影響全局的postList 59 let postList = [...this.state.postList] 60 postList.splice(index,1) 61 // 數組刪除操作用splice 62 this.setState({ 63 postList, 64 }) 65 } 66 } 67 68 export default App

這樣,就可以通過react語法簡單實現表單提交增加、刪除操作!

React---簡單實現表單點擊提交插入、刪除操作