Overview
- Sublists can be grouped without adding additional nodes to the DOM
- Simple understanding: empty tags
- <></> or <></>
render() { return ( <> <ChildA /> <ChildB /> <ChildC /> </> ) }
motivation
- The following code is an example. If the Columns component returns multiple td elements to achieve the effect, but if we use the div parent element in the Columns component, the td element will be invalidated. Fragment can solve this problem.
// const Table = () => { render() { return ( <table> <tr> <Columns /> </tr> </table> ) } } // const Columns = () => { render() { return ( <div> <td>Hello</td> <td>World</td> </div> ) } } //The above code output:<table> <tr> <div> <td>Hello</td> <td>World</td> </div> </tr> </table> // At this time td is invalid, you can use Fragemengt to solve this problem//usage:// const Columns = () => { render() { return ( <> <td>Hello</td> <td>World</td> </> ) } } // Through the above method, we can output the table correctly:<table> <tr> <td>Hello</td> <td>World</td> </tr> </table>
Phrase grammar
- A new and shorter, empty tag-like syntax can be used to declare Fragments
- <> </>
- Key or attributes are not supported
const Cloumns = () => { render() { return ( <> <td>Hello</td> <td>World</td> </> ) } }
Fragments with key
- Fragments declared using explicit <> syntax may have keys
- key is the only property that can be passed to a Fragment
function Glossary(props) { return ( <dl> {(item => ( // Without `key`, React will issue a key warning < key={}> <dt>{}</dt> <dd>{}</dd> </> ))} </dl> ) }
This is the end of this article about React's brief analysis of how to use Fragments. For more related React Fragments, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!