import React,{ Component,Fragment } from 'react';
import Item from './item';
import './app.css'
class APP extends Component{
constructor(props){
super(props);
this.state={
inputVal1:'',
inputVal2:'',
munu:[
{taste:'清淡', vegetables:'白菜'},
{taste:'麻', vegetables:'青菜'},
{taste:'咸', vegetables:'花菜'},
{taste:'香辣', vegetables:'香菜'},
{taste:'酸辣', vegetables:'萝卜'},
{taste:'咸味', vegetables:'冬瓜'},
]
}
}
// 接受输入框内的参数
onChange1 = (e) => {
this.setState({
inputVal1:e.target.value,
})
}
onChange2 = (e) =>{
this.setState({
inputVal2:e.target.value,
})
}
// 添加按钮
add = () =>{
const {munu,inputVal1,inputVal2} =this.state;
this.setState({
munu:[...munu,{taste:inputVal1,vegetables:inputVal2}]
})
}
// 给勾选时添加isChecked:checked
isCheckbox =(e,index) =>{
const {munu} =this.state;
// console.log(111,e.target.checked,index)
const arr=munu.map((item,ind)=>{
// return index===ind ? {item,isCheckbox: e.target.checked} : item;
// 1.注意返回时item需要解析出来,则添加...来解析
// 2.e.target.checked来判断是否勾选返回值为布尔值true,false
return index===ind ? {...item,isChecked: e.target.checked} : item;
})
this.setState({
munu:arr
})
}
// 删除按钮触发
delItem =(e) => {
this.setState({
// filter也是来遍历数组munu,过滤(遍历munu,让每一项的item中isChecked不等于true的返回给数组munu)
munu:this.state.munu.filter((item)=> item.isChecked !==true )
})
}
render(){
return (
<Fragment>
<div>
口味:<input value={this.state.inputVal1} onChange={this.onChange1} /> 蔬菜:<input value={this.state.inputVal2} onChange={this.onChange2} /> <button onClick={this.add}>添加</button> <button onClick={this.delItem}>删除</button>
<ul>
<div>全选:<input type='checkbox' /></div>
<div id='list'>
{this.state.munu.map((item,index)=>
<Item isCheckbox={this.isCheckbox}
index={index}
content={item}
key={index}
/>)}
</div>
</ul>
</div>
</Fragment>
)
}
};
export default APP;
——————————————————————————————————————————————————————————————————————————————————————————————————————
子篇:
import React,{Component,Fragment} from 'react';
class Item extends Component{
render(){
const {content,isCheckbox,index} =this.props;
return(
<Fragment>
<div className='list'>
{/* onClick={(e)=>isCheckbox(e,index)}触发时有个隐式形参e,用e.target.checked找到勾选状态 */}
{/* checked={!!content.isChecked}用!!两个非转为布尔形解决删除一个后遗留下来的勾选 */}
<input type='checkbox' checked={!!content.isChecked} onClick={(e)=>isCheckbox(e,index)}/>
<li>{content.taste},{content.vegetables}</li>
</div>
</Fragment>
)
}
}
export default Item;