React里的Fragment标签的具体使用
慢谷 人气:0react return里返回多个元素值要有父标签包裹。
React.Fragment组件能够在不额外创建 DOM 元素的情况下,让 render()方法中返回多个元素。相当于空标签<></>。
<></>包裹多个元素↓:
import React, { Component, Fragment } from "react"; import "./App.css"; class App extends Component { render() { return ( <> <div> <input /> <button>按钮</button> </div> <ul> <li>哈</li> <li>咯</li> </ul> </> ); } } export default App;
使用Fragment标签↓:
和<></>实现效果一致。
import React, { Component, Fragment } from "react"; import "./App.css"; class App extends Component { render() { return ( <Fragment> <div> <input /> <button>按钮</button> </div> <ul> <li>哈</li> <li>咯</li> </ul> </Fragment> ); } } export default App;
<React.Fragment>就不用在头部引入了↓:
import React, { Component } from "react"; import "./App.css"; class App extends Component { render() { return ( <React.Fragment> <div> <input /> <button>按钮</button> </div> <ul> <li>哈</li> <li>咯</li> </ul> </React.Fragment> ); } } export default App;
使用<div>包裹多个标签就会多一层嵌套↓:
import React, { Component, Fragment } from "react"; import "./App.css"; class App extends Component { render() { return ( <div> <div> <input /> <button>按钮</button> </div> <ul> <li>哈</li> <li>咯</li> </ul> </div> ); } } export default App;
<></>和Fragment标签的区别
Fragment标签支持能接受键值或属性,可以遍历循环渲染元素
import React, { Component } from "react"; import "./App.css"; const list = [ { id: 0, name: "凤凰火", description: "最肉" }, { id: 1, name: "彼岸花", description: "花花" }, ]; class App extends Component { render() { return list.map((item) => ( <React.Fragment key={item.id}> <li> {item.name}是{item.description} </li> </React.Fragment> )); } } export default App;
加载全部内容