<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{margin:0;padding:0;}
li{ width:210px;
height:20px;
list-style:none;}
#app{width:200px;
margin:50px auto;
}
span{float:right;
width:25px;
height:25px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="app"></div>
<script src="node_modules/babel-standalone/babel.js"></script>
<script src="node_modules/react/umd/react.development.js"></script>
<script src="node_modules/react-dom/umd/react-dom.development.js"></script>
<script type="text/babel">
class Content extends React.Component{
constructor(){
super(...arguments);
this.state={
arr:[{id:Math.random()*10,
name:'react'
},
{id:Math.random()*10,
name:'vue'
}]
}
}
//删除列表项
removeItem=(index)=>{
console.log(index)
const arr=this.state.arr;
for(var i=0;i<arr.length;i++){
if(index==i){
//console.log(arr[i])
arr.splice(arr[i],1);
}
}
this.setState({arr})
}
//输入列表项,按回车键结束
handleclick=(e)=>{
const {target,keyCode}=e;
const arr=this.state.arr
if(keyCode==13){
arr.push({id:Math.random()*10,name:target.value})
target.value=null;
this.setState({arr})
return;
}
}
render(){
return(
<div>
<input type="text" onKeyDown={this.handleclick} />
{this.state.arr.length>0&&
this.state.arr.map((item,index)=>{
return (<li key={index}>{item.name}<span onClick={this.removeItem.bind(this,index)}>x</span></li>)
})
}
</div>)
}
}
class App extends React.Component{
render(){
return (<div><Content/></div>)
}
}
ReactDOM.render(<App/>,document.getElementById("app"));
</script>
</body>
</html>