React-核心JSX语法五

223 阅读2分钟

需要学习掌握的知识点

1.fifter的用法

2.求偶数%

jsx列表渲染

列表渲染

真实开发中我们会从服务器请求到大量的数据,数据会以列表的形式存储:

  • 比如歌曲、歌手、排行榜列表的数据;
  • 比如商品、购物车、评论列表的数据;
  • 比如好友消息、动态、联系人列表的数据;

在React中并没有像Vue模块语法中的v-for指令,而且需要我们通过JavaScript代码的方式组织数据,转成JSX:

  • 很多从Vue转型到React的同学非常不习惯,认为Vue的方式更加的简洁明了;
  • 但是React中的JSX正是因为和JavaScript无缝的衔接,让它可以更加的灵活;
  • 另外我经常会提到React是真正可以提高我们编写代码能力的一种方式;

如何展示列表呢?

  • 在React中,展示列表最多的方式就是使用数组的map高阶函数;

数组的map函数语法如下:

  • callback:生成新数组元素的函数,使用三个参数:
    • currentValue

      callback 数组中正在处理的当前元素。

    • index可选

      callback 数组中正在处理的当前元素的索引。

    • array可选

      map 方法调用的数组。

  • thisArg可选:执行 callback 函数时值被用作this
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])

我们来演练一下之前的案例:


class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      names:['abc','cba','nba','mba','dna'],
      numbers:[110,123,50,32,55,10,8,333]
    }
  }

  render() {
    return (
      <div>
        <h2>名字列表</h2>
        <ul>
          {
            this.state.names.map(item => {
              return <li>{item}</li>
            })
          }
        </ul>
        <h2>数字列表</h2>
        <ul>
          {
            this.state.numbers.map(item => {
              return <li>{item}</li>
            })
          }
        </ul>
      </div>
    )
  }
}

ReactDOM.render(<App/>document.getElementById("app"));

数组处理

很多时候我们在展示一个数组中的数据之前,需要先对它进行一些处理:

  • 比如过滤掉一些内容:filter函数
  • 比如截取数组中的一部分内容:slice函数

比如我当前有一个数组中存放了一系列的数字:[10, 30, 120, 453, 55, 78, 111, 222]

案例需求:获取所有大于50的数字,并且展示前3个数组

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      numbers: [10301204535578111222]
    }
  }

  render() {
    return (
      <div>
        <h2>数字列表</h2>
        <ul>
          {
            this.state.numbers.filter(item => item >= 50).slice(0, 3).map(item => {
              return <li>{item}</li>
            })
          }
        </ul>
      </div>
    )
  }
}

ReactDOM.render(<App/>document.getElementById("app"));