父组件http请求 传值给子组件
import React from 'react';
import Title from './sytled-components/Wrapper'
import Item from './components/Item'
class App extends React.Component{
constructor(props){
super(props);
this.state={
playlists:[]
}
}
render(){
return (
<div className="App">
<Title>
{this.state.playlists.map(item=>{
return (
<div className="item" key={item.id}>
<Item items={item}/>
</div>
)
})}
</Title>
</div>
)
}
componentDidMount(){
var url = "https://music.aityp.com/top/playlist?cat=华语"
this.$http.get(url).then(res=>{
this.setState({
playlists:res.data.playlists
})
})
}
}
export default App;
子组件接受传值 渲染对象
import React from 'react'
import Title from '../sytled-components/Wrapper'
class Item extends React.Component{
constructor(props){
super(props)
}
render(){
return(<div>
<Title>
<img src={this.props.items.coverImgUrl}></img>
<p>{this.props.items.name}</p>
</Title>
</div>)
}
}
export default Item
子组件携带值传递事件给父组件
render(){
return(<div onClick={this.handleClick.bind(this,this.props.items.id)}>
//绑定一个点击事件
<Title>
<img src={this.props.items.coverImgUrl}></img>
<p>{this.props.items.name}</p>
</Title>
</div>)
}
handleClick=(id)=>{
this.props.deleteItem(id)
}
父组件接受事件,通过过滤器
render(){
return (
<div className="App">
<Title>
{this.state.playlists.map(item=>{
return (
<div className="item" key={item.id}>
<Item deleteItem={this.handleDelete.bind(this)} items={item}/> //接收事件
</div>
)
})}
</Title>
</div>
)
}
handleDelete(id){
var playlists = this.state.playlists.filter(item=>item.id!==id)
// 过滤掉id不同的item形成新的数组
this.setState({
playlists
})
}