React 片段

如何使用 React 片段創建不可見的 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> </> ) } }