数组渲染
import React from 'react' import ReactDom from 'react-dom' class Welcome extends React.Component { constructor(props) { super(props) this.state = { list: [{ title: '第一节课 React事件', content: '事件内容' }, { title: '第二节课 React数据传递', content: '数据传递' }, { title: '第三节课 条件渲染', content: '条件渲染内容' }] } } 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) // 或者map方法 let listArr = this.state.list.map((item, key) => { return ( <li key={ key }> <h3>{ key + 1 + ' - ' + item['title'] }</h3> <p>{ item['content'] }</p> </li> ) }) } return ( <div> <h1>今天课程内容</h1> <ul> { listArr } </ul> </div> ) } } ReactDom.render(<Welcome />, document.getElementById('root')) 复制代码
组件式循环
import React from 'react' import ReactDom from 'react-dom' function ListItem(props) { return ( <li> <h3>{ props.index + 1 + ' - ' + props.data['title'] }</h3> <p>{ props.data['content'] }</p> </li> ) } class Welcome extends React.Component { constructor(props) { super(props) this.state = { list: [{ title: '第一节课 React事件', content: '事件内容' }, { title: '第二节课 React数据传递', content: '数据传递' }, { title: '第三节课 条件渲染', content: '条件渲染内容' }] } } render() { let listArr = this.state.list.map((item, key) => { return ( <ListItem data={ item } key={ key } index={ key }></ListItem> ) }) return ( <div> <h1>今天课程内容</h1> <ul> { listArr } </ul> </div> ) } } ReactDom.render(<Welcome />, document.getElementById('root')) 复制代码
循环汇总
import React from 'react' import ReactDom from 'react-dom' function ListItem(props) { return ( <li> <h3>{ props.index + 1 + ' - ' + props.data['title'] }</h3> <p>{ props.data['content'] }</p> </li> ) } class ListItem2 extends React.Component { constructor(props) { super(props) this.state = {} } render() { return ( <li onClick={ (e) => { this.onOpenShowMsg(this.props.index, this.props.data) }}> <h3>{ this.props.index + 1 + ' - ' + this.props.data['title'] }</h3> <p>{ this.props.data['content'] }</p> </li> ) } onOpenShowMsg = (index, data) => { console.log(index + ' - ' + data.title) } } class Welcome extends React.Component { constructor(props) { super(props) this.state = { list: [{ title: '第一节课 React事件', content: '事件内容' }, { title: '第二节课 React数据传递', content: '数据传递' }, { title: '第三节课 条件渲染', content: '条件渲染内容' }] } } render() { let listArr = this.state.list.map((item, key) => { return ( <ListItem data={ item } key={ key } index={ key }></ListItem> ) }) return ( <div> <h1>今天课程内容</h1> <ul> { listArr } </ul> <h1>第二个循环</h1> <ul> { this.state.list.map((item, key) => { return ( <div> <ListItem2 data={ item } key={ key } index={ key }></ListItem2> </div> ) }) } </ul> </div> ) } } ReactDom.render(<Welcome />, document.getElementById('root'))