React高级——Fragment以及[ ]

class App extends Component {
  render() {
    return (
      
); } }

然后这个List如下(会报错,下面是错误的)

const List = (props) => {
  return (
      
  • list 1
  • list 1
  • ) }

    这样子会报错,因为,只能return一个子元素,所以要用div把这两个li包裹起来,如下所示

    const List = (props) => {
      return (
          
  • list 1
  • list 1
  • ) }

    但是这样子语义上不好,ul子元素就直接接个li,再多个div不是多余么,所以使用Fragment来进行包裹

    import React, { Component, Fragment } from 'react';
    

    从react中把Fragment 导出
    然后

    const List = (props) => {
      return (
          
               
  • list 1
  • list 1
  • ) }

    这样子用Fragment 包裹后,页面最终出来的是

    • list 1
    • list 1

    然后用[ ]包裹也能实现上面的效果,只是里面的元素要加个key就行

    const List = (props) => {
      return (
          [
               
  • list 1
  • list 1
  • ] ) }

    因为是个数组,所以里面每个元素都要带key,这个key的内容随便你写什么都可以,只要保证它的唯一性

    你可能感兴趣的:(React高级——Fragment以及[ ])