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循环,要么就用数组方法遍历
虽然很麻烦,但是没办法…