父组件http请求 传值给子组件

    1. import React from 'react';
    2. import Title from './sytled-components/Wrapper'
    3. import Item from './components/Item'
    4. class App extends React.Component{
    5. constructor(props){
    6. super(props);
    7. this.state={
    8. playlists:[]
    9. }
    10. }
    11. render(){
    12. return (
    13. <div className="App">
    14. <Title>
    15. {this.state.playlists.map(item=>{
    16. return (
    17. <div className="item" key={item.id}>
    18. <Item items={item}/>
    19. </div>
    20. )
    21. })}
    22. </Title>
    23. </div>
    24. )
    25. }
    26. componentDidMount(){
    27. var url = "https://music.aityp.com/top/playlist?cat=华语"
    28. this.$http.get(url).then(res=>{
    29. this.setState({
    30. playlists:res.data.playlists
    31. })
    32. })
    33. }
    34. }
    35. export default App;

    子组件接受传值 渲染对象

    1. import React from 'react'
    2. import Title from '../sytled-components/Wrapper'
    3. class Item extends React.Component{
    4. constructor(props){
    5. super(props)
    6. }
    7. render(){
    8. return(<div>
    9. <Title>
    10. <img src={this.props.items.coverImgUrl}></img>
    11. <p>{this.props.items.name}</p>
    12. </Title>
    13. </div>)
    14. }
    15. }
    16. export default Item

    子组件携带值传递事件给父组件

    1. render(){
    2. return(<div onClick={this.handleClick.bind(this,this.props.items.id)}>
    3. //绑定一个点击事件
    4. <Title>
    5. <img src={this.props.items.coverImgUrl}></img>
    6. <p>{this.props.items.name}</p>
    7. </Title>
    8. </div>)
    9. }
    10. handleClick=(id)=>{
    11. this.props.deleteItem(id)
    12. }

    父组件接受事件,通过过滤器

    1. render(){
    2. return (
    3. <div className="App">
    4. <Title>
    5. {this.state.playlists.map(item=>{
    6. return (
    7. <div className="item" key={item.id}>
    8. <Item deleteItem={this.handleDelete.bind(this)} items={item}/> //接收事件
    9. </div>
    10. )
    11. })}
    12. </Title>
    13. </div>
    14. )
    15. }
    16. handleDelete(id){
    17. var playlists = this.state.playlists.filter(item=>item.id!==id)
    18. // 过滤掉id不同的item形成新的数组
    19. this.setState({
    20. playlists
    21. })
    22. }