react纯手写全选与取消全选
Posted mdge
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react纯手写全选与取消全选相关的知识,希望对你有一定的参考价值。
<!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>
<script src="js/react.development.js"></script>
<script src="js/react-dom.development.js"></script>
<script type="text/javascript" src="js/babel.min.js"></script>
</head>
<body>
<div id="my"></div>
<script type="text/babel">
class FormSelectT extends React.Component{
constructor(){
super()
this.state={
checkAll: false,
checkArr: [{name:‘看书‘,status:false},{name:‘睡觉‘,status:false},{name:‘喝水‘,status:true}]
}
}
changeAll(e){
let {checkAll,checkArr} = this.state;
let check = e.target.checked;
checkAll = check;
checkArr.map((val)=>{
return val.status = check
})
this.setState({
checkAll: checkAll,
checkArr: checkArr
})
}
listControllAll(e){
let {checkArr,checkAll} = this.state;
checkArr.map((val)=>{
if(val.name == e.name){
return val.status = e.status
}
})
this.setState({
checkArr:checkArr
});
let changecheckAll=checkArr.every((val)=>{
return val.status
});
this.setState({
checkAll:changecheckAll
})
}
render(){
let {checkAll,checkArr} = this.state;
let self = this;
let arrHobby = checkArr.map((val,index)=>{
return <FormSelectB key={index} {...val} listControllAll={self.listControllAll.bind(self)}/>
})
return (
<div>
<input type="checkbox" checked={checkAll} onChange={(e)=>this.changeAll(e)}/><label>全选</label>
<ul>
{arrHobby}
</ul>
</div>
)
}
}
class FormSelectB extends React.Component{
constructor(props){
super(props)
this.state={
name:props.name,
status:props.status
}
}
changeList(e){
let check = e.target.checked;
let {name,status} = this.state;
this.setState({
status:check
},function(){
this.props.listControllAll({name:this.state.name,status:this.state.status})
})
}
componentWillReceiveProps(nextProps,prevProps){
let {status} = this.state
if(nextProps.status!=prevProps.status){
this.setState({
status:nextProps.status
})
}
}
render(){
let {name,status} = this.state;
return(
<li><input type="checkbox" checked={status} onChange={(e)=>{this.changeList(e)}}/><label>{name}</label></li>
)
}
}
ReactDOM.render(
<div>
<FormSelectT/>
</div>,
document.getElementById(‘my‘)
)
</script>
</body>
</html>
以上是关于react纯手写全选与取消全选的主要内容,如果未能解决你的问题,请参考以下文章