1.父组件发送请求,将取到的数组通过自定义传参的方式传给子组件,在子组件里面遍历渲染数据
import React from 'react';
import Delete from './components/Delete'
import './App.css'
class App extends React.Component{
constructor(props){
super(props);
this.state={
playlists:[]
}
}
render() {
return(
<div className="container">
<Delete content={this.state.playlists} //自定义属性传参>
</Delete>
</div>
)
}
componentDidMount(){
var url='https://music.aityp.com/top/playlist?cat=华语'
this.$http.get(url).then(res=>{
var playlists=res.data.playlists;
this.setState({
playlists
})
})
}
}
export default App;
2.子组件中通过this.props接收参数,并渲染数据
import React from 'react'
import './Delete.css'
class Delete extends React.Component{
constructor(props){
super(props)
}
render() {
return(
<div className="wrap">
{this.props.content.map((item,index)=>{
return(<div className="list" key={index} >
<img className="pic" src={item.coverImgUrl}></img>
<p className="name">{item.name}</p>
<p className="nickname">by {item.creator.nickname}</p>
</div>)
})}
</div>
)
}
}
export default Delete
3.子组件中定义一个点击事件,将下标传到父组件中
import React from 'react'
import './Delete.css'
class Delete extends React.Component{
constructor(props){
super(props)
this.handleClick=this.handleClick.bind(this) //子组件的属性接收一个父组件的方法
}
render() {
return(
<div className="wrap">
{this.props.content.map((item,index)=>{
return(<div className="list" key={index} index={index}
onClick={this.handleClick}>
<img className="pic" src={item.coverImgUrl}></img>
<p className="name">{item.name}</p>
<p className="nickname">by {item.creator.nickname}</p>
</div>)
})}
</div>
)
}
handleClick(){ //在子组件中,调用这个方法,向父组件传参
this.props.deleteItem(this.props.index)
}
}
export default Delete
4.在父组件中通过传过来的index点击删除
render() {
return(
<div className="container">
<Delete content={this.state.playlists}
//向子组件传递一个事件
deleteItem={this.handleDelete.bind(this)}></Delete>
</div>
)
}
handleDelete(index){
var playlists=this.state.playlists;
playlists.splice(index,1)
this.setState({
playlists:playlists
})
}