父组件:
父传子:父:<Child name={...对象}/>
子:this.props.key
render() { //解构 let { data } = this.state; return ( <ul> { data.map((item, index) => { return <List key={index} {...item} change={index => this.change(index)} /> }) } </ul> ) } change(id) { //子传父 let newarr = this.state.data; newarr.filter(item => { if (item.id == id) { item.flag = !item.flag } }) //刷新数据 this.setState({ data:newarr }) }
子组件:
render() { return ( <li> <img src={this.props.img} /> <span className="name">{this.props.name}</span> <button onClick={() => { this.props.change(this.props.id) }} className={this.props.flag ? "grey" : "green"}> {this.props.flag ? "已添加" : "添加"}</button> </li> ) }
原文地址:https://www.cnblogs.com/fairylee/p/10996300.html
时间: 2024-09-30 11:00:09