React列表循环渲染

React没有像VUE那样强大的v-for,所以就得用for循环或者数组遍历方法了

下面来举一个例子吧,写一个嵌套的组件

首先我们先创建一个子类组件

class ListItem2 extends React.Component{
  constructor(props){
    super(props)
  }

  render(){
    return(
      <li onClick={(event)=>{this.clickEvent(
        this.props.index,
        this.props.data.title,
        event
      )}}>
      <h3>{this.props.data.title}</h3>
      <p>{this.props.data.content}</p>
    </li>
     )
  }
  clickEvent=(index,title,event)=>{
   alert(index+title).  //点击每个li标签,弹窗
  }
}

再创建一个父类组件

class Welcome extends React.Component{
  constructor(props){
    super(props)
    this.state={
      list:[
        {
          title:'gogoing',
          content:'刀妹'
        },
        {
          title:'gogoing1',
          content:'刀妹1'
        },
        {
          title:'gogoing2',
          content:'刀妹2'
        }
      ]
    }
  }
  render(){
    // let listArr = [];
    // for(let i = 0;i<this.state.list.length;i++){
    //   let item =(
    //     <li>
    //       <h3>{this.state.list[i].title}</h3>
    //       <p>{this.state.list[i].content}</p>
    //     </li>
    //   )
    //   listArr.push(item)
    // }
    let listArr = this.state.list.map((item,index)=>{
    return (
     <ListItem2 data={item} index={index} key={index}></ListItem2>
    )
    });

    return (
      <div>
        <h1>
          今天课程内容
        </h1>
        <ul>
          {listArr}
          <li>
            <h3>这是标题</h3>
            <p>这是内容</p>
          </li>
        </ul>
      </div>
    )
  }
}
循环数组,要么用最原始的for循环,要么就用数组方法遍历

虽然很麻烦,但是没办法…

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值