父传子
这里我们父组件向子组件<Header></Header>传递this.state.isEdit
的变量
//父组件传值
constructor(props) {
super(props);
this.changeEdit = this.changeEdit.bind(this)
this.selectOne = this.selectOne.bind(this)
this.selectAll = this.selectAll.bind(this)
}
state={
carts:[],
isEdit:false,//是否是编辑状态
checkedAll:false,//全选的状态
}
....................
<Header changeEdit={this.changeEdit} isEdit={!this.state.isEdit}></Header>
//子组件接收
let isEdit = this.props.isEdit
子传父
//父组件
constructor(props) {
super(props);
this.changeEdit = this.changeEdit.bind(this)
}
state={}//这里是定义我们的变量
.........
render() {
return (
<Header changeEdit={this.changeEdit} isEdit={!this.state.isEdit}></Header>
)
}
........
/////////////编辑与完成的切换事件
changeEdit(){
this.setState({
isEdit:!this.state.isEdit
})
console.log(this.state.isEdit)
}
//子组件
render() {
let isEdit = this.props.isEdit
console.log("11111111",isEdit)
let { item } = this.props;
return (
<div className = "header bg-fff fcb" >
<Link to="/home/detail">
<i className="iconfont icon-left f20 ml-10 fff"></i></Link>
<span > 购物车 </span>
<span className = "mr-10 fff"
onClick={()=>{this.props.changeEdit()}} > {isEdit?"编辑":"完成"} </span>
</div>
)
}
点击事件()=>{this.props.changeEdit()}
需要使用箭头函数
父组件向子组件传值的时候出现第一次为空值,第二次有值,但在子组件中不渲染数据该怎么办?
解决的办法是不要一次性把所有的数据传递给子组件,而是通过在父组件遍历数据后,把item传给子组件
//父组件
render() {
let {carts,checkedAll}=this.state
console.log("checkedAll",checkedAll)
return (
<div className="cart">
<Header changeEdit={this.changeEdit}
isEdit={!this.state.isEdit}></Header>
//遍历数据的部分
{carts.map((item,index)=>{
return <Main item={item}
index={index} key={index} isEdit={!this.state.isEdit}
selectOne={this.selectOne}></Main>
})}
<CountFooter checkedAll={checkedAll}
selectAll={this.selectAll}></CountFooter>
<div className="kongbai"></div>
<Footer page="cart"></Footer>
</div>
)
}
//子组件
render(){
let isEdit = this.props.isEdit
let {item={}} = this.props
return(
<ul className="cart-list">
<li className="item bg-fff flex jc-sa aic bdb">
<input type="checkbox" className="inputCheck" checked=
{item.checked} onClick={()=>{this.props.selectOne(this.props.index)}}/>
<img className="cart-img" src={item.imgUrl} alt="" />
<p className="flex2 aic">
<span>[鲜花]{item.goodName}</span>
<span className="orange mt-10">¥{item.price}</span>
</p>
{
isEdit?<p className='price jc-sa flex'>x12</p>: <div><p
className="operate jc-sa flex">
<span>-</span>
<span>2</span>
<span>+</span>
</p>
<span>删除</span>
</div>
}
</li>
</ul>
)
}
网友评论