ui.png

    1. //src/components/Item.js
    2. import React from 'react';
    3. import '../Item.css'
    4. class Item extends React.Component{
    5. constructor(props){
    6. super(props)
    7. }
    8. render(){
    9. return (
    10. <div onClick={this.handleClick.bind(this,this.props.data.id)} className="item">
    11. <img className="cover" src={this.props.data.coverImgUrl} />
    12. <p className="name">{this.props.data.name}</p>
    13. </div>
    14. )
    15. }
    16. handleClick=(id)=>{
    17. /* 在子组件调用方法,向组件传参 */
    18. this.props.deleteItem(id)
    19. console.log(id)
    20. }
    21. }
    22. export default Item;
    1. //src/App.js
    2. import React from 'react';
    3. import Item from './components/Item'
    4. import axios from 'axios'
    5. import './App.css'
    6. class App extends React.Component{
    7. constructor(props){
    8. super(props);
    9. this.state = {
    10. playlists:[]
    11. }
    12. }
    13. render(){
    14. return (
    15. <div className="container">
    16. {/* 子组件的属性接收父组件传递过来的方法 */}
    17. {this.state.playlists.map(item=>{
    18. return (
    19. <div key={item.id}>
    20. <Item data={item} deleteItem = {this.handleDelete.bind(this)}></Item>
    21. </div>
    22. )
    23. })}
    24. </div>
    25. )
    26. }
    27. handleDelete(id){
    28. console.log(id)
    29. var playlists = this.state.playlists.filter(item=>item.id !== id)
    30. this.setState({
    31. playlists
    32. })
    33. }
    34. componentDidMount(){
    35. var url = "https://music.aityp.com/top/playlist";
    36. axios.get(url).then(res=>{
    37. // console.log(res.data.playlists)
    38. this.setState({
    39. playlists:res.data.playlists
    40. })
    41. })
    42. }
    43. }
    44. export default App;