如何使用React.Fragment来创建不可见的HTML标签

69 阅读1分钟

如何使用React.Fragment来创建不可见的HTML标签

请注意我是如何将返回值包裹在一个div 。这是因为一个组件只能返回一个单一的元素,如果你想要多个,你需要用另一个容器标签来包裹它。

然而这在输出中造成了不必要的div 。你可以通过使用React.Fragment 来避免这种情况。

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

class BlogPostExcerpt extends Component {
  render() {
    return (
      <React.Fragment>
        <h1>{this.props.title}</h1>
        <p>{this.props.description}</p>
      </React.Fragment>
    )
  }
}

它还有一个非常好的速记语法<></> ,只在最近的版本中支持(和Babel 7+)。

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

class BlogPostExcerpt extends Component {
  render() {
    return (
      <>
        <h1>{this.props.title}</h1>
        <p>{this.props.description}</p>
      </>
    )
  }
}