1.输入框的值新增到数组列表
import React, { Component } from 'react'
import './css/01-index.css'
export default class app extends Component {
a = 100;
myref = React.createRef()
state = {
list:[{
id: "1",
mytext:"1111"
}]
};
render() {
var newList= this.state.list.map((item,index) => <li key={index}>{item.key}</li> )
return (
<div>
<input ref={this.myref} />
<button onClick={this.handleClick2}>add2</button>
<ul>
{
this.state.list.map((item,index)=>
<li key={item.id}> {item.mytext}
</li>
)
}
</ul>
</div>
)
}
handleClick2 = () => {
// console.log("click2", this.myref.current.value)
this.state.list.push({ "mytext": this.myref.current.value,id:Math.random()*111111})
this.setState({list:this.state.list})
}
}
2. 删除列表的某项值
{/* 删除方案1 bind 方法*/}
<input onClick={this.handleDelClick.bind(this, item.id)} type="button" value="del" />
{/* 删除方案2 匿名箭头函数 */}
<input onClick={()=>this.handleDelClick(index)} type="button" value="del" />
3. 条件判断无列表显示的相关内容
{/* 条件渲染 方案1 */}
<div> {this.state.list.length > 0 ? null : "待办事项暂无~"}</div>
{/* 条件渲染 方案2 */}
<div> {this.state.list.length === 0 && "待办事项暂无!"}</div>
{/* 条件渲染 方案3 */}
<div className={this.state.list.length === 0?'':'hidden'}> 待办事项暂无!</div>
代码如下
import React, { Component } from 'react'
import './css/01-index.css'
export default class app extends Component {
a = 100;
myref = React.createRef()
state = {
list:[{
id: "1",
mytext:"1111"
},{
id: "2",
mytext:"2222"
},{
id: "3",
mytext:"3333"
}]
};
render() {
var newList= this.state.list.map((item,index) => <li key={index}>{item.key}</li> )
return (
<div>
<input ref={this.myref} />
<button onClick={this.handleClick2}>add2</button>
<ul>
{
this.state.list.map((item,index)=>
<li key={item.id}>
{item.mytext}
{/* 删除方案1 bind 方法*/}
{/* <input onClick={this.handleDelClick.bind(this, item.id)} type="button" value="del" /> */}
{/* 删除方案2 匿名箭头函数 */}
<input onClick={()=>this.handleDelClick(index)} type="button" value="del" />
</li>
)
}
</ul>
{/* 条件渲染 方案1 */}
{/* <div> {this.state.list.length > 0 ? null : "待办事项暂无~"}</div> */}
{/* 条件渲染 方案2 */}
{/* <div> {this.state.list.length === 0 && "待办事项暂无!"}</div> */}
{/* 条件渲染 方案3 */}
<div className={this.state.list.length === 0?'':'hidden'}> 待办事项暂无!</div>
</div>
)
}
handleClick2 = () => {
// console.log("click2", this.myref.current.value)
this.state.list.push({ "mytext": this.myref.current.value,id:Math.random()*111111})
this.setState({list:this.state.list})
}
handleDelClick = (id) => {
console.log("click2", id)
let newlist = this.state.list.concat() //拷贝一个数组 slice(0) [...arr] Array.from(arr) Object.assign([],arr);
newlist.splice(id, 1)
this.setState({list:newlist})
}
}