1.父组件发送请求,将取到的数组通过自定义传参的方式传给子组件,在子组件里面遍历渲染数据

  1. import React from 'react';
  2. import Delete from './components/Delete'
  3. import './App.css'
  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="container">
  14. <Delete content={this.state.playlists} //自定义属性传参>
  15. </Delete>
  16. </div>
  17. )
  18. }
  19. componentDidMount(){
  20. var url='https://music.aityp.com/top/playlist?cat=华语'
  21. this.$http.get(url).then(res=>{
  22. var playlists=res.data.playlists;
  23. this.setState({
  24. playlists
  25. })
  26. })
  27. }
  28. }
  29. export default App;

2.子组件中通过this.props接收参数,并渲染数据

  1. import React from 'react'
  2. import './Delete.css'
  3. class Delete extends React.Component{
  4. constructor(props){
  5. super(props)
  6. }
  7. render() {
  8. return(
  9. <div className="wrap">
  10. {this.props.content.map((item,index)=>{
  11. return(<div className="list" key={index} >
  12. <img className="pic" src={item.coverImgUrl}></img>
  13. <p className="name">{item.name}</p>
  14. <p className="nickname">by {item.creator.nickname}</p>
  15. </div>)
  16. })}
  17. </div>
  18. )
  19. }
  20. }
  21. export default Delete

3.子组件中定义一个点击事件,将下标传到父组件中

  1. import React from 'react'
  2. import './Delete.css'
  3. class Delete extends React.Component{
  4. constructor(props){
  5. super(props)
  6. this.handleClick=this.handleClick.bind(this) //子组件的属性接收一个父组件的方法
  7. }
  8. render() {
  9. return(
  10. <div className="wrap">
  11. {this.props.content.map((item,index)=>{
  12. return(<div className="list" key={index} index={index}
  13. onClick={this.handleClick}>
  14. <img className="pic" src={item.coverImgUrl}></img>
  15. <p className="name">{item.name}</p>
  16. <p className="nickname">by {item.creator.nickname}</p>
  17. </div>)
  18. })}
  19. </div>
  20. )
  21. }
  22. handleClick(){ //在子组件中,调用这个方法,向父组件传参
  23. this.props.deleteItem(this.props.index)
  24. }
  25. }
  26. export default Delete

4.在父组件中通过传过来的index点击删除

  1. render() {
  2. return(
  3. <div className="container">
  4. <Delete content={this.state.playlists}
  5. //向子组件传递一个事件
  6. deleteItem={this.handleDelete.bind(this)}></Delete>
  7. </div>
  8. )
  9. }
  10. handleDelete(index){
  11. var playlists=this.state.playlists;
  12. playlists.splice(index,1)
  13. this.setState({
  14. playlists:playlists
  15. })
  16. }