功能需求
//Fragment可以看做是一个包裹行的标签
import React, { Component, Fragment}from 'react';
class App extends Component {
//这里是初始的数据,用的constructor构造函数的时候,需要用到super(),主要是为了解决this问题
constructor () {
super()
this.state = {
proList: [
'item1',
'item2',
'item3'
],
inputValue: ''
}
}
//对页面进行渲染,内部需要return(),因为其为function render () {},函数有返回值需要return
render () {
return (
//上面说过,相当于包裹函数,因为很多标签需要放置在同一个父标签内部,react规则
<Fragment>
<ul>
{
//显然列表数据
this.state.proList.map((value,index) => {
return (
//点击按钮删除,需要传递index是为了删除那一项
<li key={index}>{value}<button onClick={this.deleteItem.bind(this,index)}>删除</button></li>
)
})
}
</ul>
// onChange事件,书写里面的数据
<textarea cols="20" rows="10" value={this.state.inputValue} onChange={this.handleInput.bind(this)}></textarea>
<br />
//点击按钮,进行数据的提交到上方的渲染列表之中
<button onClick={this.submite.bind(this)}>发布</button>
</Fragment>
)
}
此函数就是为了书写textarea标签之中的数据
handleInput (e) {
this.setState({
inputValue: e.target.value
})
}
删除函数,需要进行数据传值
deleteItem (index) {
// 为了不修改原始数据
let proList = [...this.state.proList]
// 数组的剪切
// arr.splice(index,index,howmany,item1,.....,itemX)直接修改数组
// index,从那一项开始,当为负数的时候,默认从末尾开始,index从0开始。
//howmany,删除多少项
//后面的是替换的作用
proList.splice(index, 1)
// console.log(proList)
this.setState({
proList
})
}
submite () {
this.setState({
// ES6数组的合并
proList: [...this.state.proList,this.state.inputValue],
inputValue: ''
})
}
}
export default App;