react渲染列表的四种方式

注意:
class方式定义的组件名首字母大写,如:News

方式一(直接在html中渲染):

import React from 'react'

class News extends React.Component {
	constructor(props) {
        super(props); // 用于父子组件传值

        this.state = {
            info: [{
                    title:'第一个标题',
                    key:'第一个key'
                },{
                    title:'第二个标题',
                    key:'第二个key'
                },{
                    title:'第三个标题',
                    key:'第三个key'
                }]
        }
    }
    
	render () {
		return (
			
    { this.state.info.map((item, key) => { return (
  • {item.title}

    {item.key}

  • ) }) }
) } } export default News;

方式二(以参数方式渲染) :

import React from 'react'

class News extends React.Component {
	constructor(props) {
        super(props); // 用于父子组件传值

        this.state = {
            info: [{
                    title:'第一个标题',
                    key:'第一个key'
                },{
                    title:'第二个标题',
                    key:'第二个key'
                },{
                    title:'第三个标题',
                    key:'第三个key'
                }]
        }
    }
    
	render () {
		let listItem_1 = this.state.info.map((item, key) => {
            return (
                
  • {item.title}

    {item.key}

  • ) }) return (
      {listItem_1}
    ) } } export default News;

    方式三(以function方式渲染) :

    import React from 'react'
    
    class News extends React.Component {
    	constructor(props) {
            super(props); // 用于父子组件传值
    
            this.state = {
                info: [{
                        title:'第一个标题',
                        key:'第一个key'
                    },{
                        title:'第二个标题',
                        key:'第二个key'
                    },{
                        title:'第三个标题',
                        key:'第三个key'
                    }]
            }
        }
        
    	listItem_2 (list) {
            let res = list.map((item, key) => {
                return (
                    
  • {item.title}

    {item.key}

  • ) }) return (
      {res}
    ) } render () { return (
    {this.listItem_2(this.state.info)}
    ) } } export default News;

    方式四(以组件方式渲染) :

    这里的ListItem组件比较复杂的情况下建议单独抽离到一个js文件,写法完全一样,只是需要将组件通过export default 暴露出来

    import React from 'react'
    
    class ListItem extends React.Component {
        constructor(props){
            super(props); // props用于父子组件传值,如果没有值可以不
        }
    
        render () {
            let info = this.props;
            return (
                

    {info.info.title}

    {info.info.key}

    ); } } class News extends React.Component { constructor(props) { super(props); // 用于父子组件传值 this.state = { info: [{ title:'第一个标题', key:'第一个key' },{ title:'第二个标题', key:'第二个key' },{ title:'第三个标题', key:'第三个key' }] } } render () { return (
    { this.state.info.map((item, index) => { return }) }
    ) } } export default News;

    你可能感兴趣的:(react)