React 基礎(chǔ)鞏固(十三)——列表渲染
列表渲染
- 在 React 中沒(méi)有像 Vue 模塊語(yǔ)法中的 v-for 指令,而是需要我們通過(guò) JS 代碼的方式組織數(shù)據(jù),轉(zhuǎn)成 JSX
- 在 React 中,展示列表最多的方式就是使用數(shù)組的 map 高階函數(shù)
- 在展示數(shù)組前,有時(shí)會(huì)進(jìn)行一些處理
- 過(guò)濾一些內(nèi)容(filter 函數(shù))
- 截取數(shù)組中的一部分內(nèi)容(slice 函數(shù))
- 列表中的 key
- 子項(xiàng)一般需要綁定 key,否則存在 Warning 警告(Each child in a list should have a unique “key”)
- key主要作用是為了提高diff算法時(shí)的效率
<script type="text/babel">
// 1.創(chuàng)建root
const root = ReactDOM.createRoot(document.querySelector("#root"));
// 2.封裝App組件
class App extends React.Component {
// 組件數(shù)據(jù)
constructor() {
super();
this.state = {
students: [
{ id: 111, name: "outman1", score: 99 },
{ id: 112, name: "outman2", score: 98 },
{ id: 113, name: "outman3", score: 194 },
{ id: 113, name: "outman4", score: 196 },
{ id: 113, name: "outman5", score: 126 },
{ id: 113, name: "outman6", score: 136 },
],
};
}
// 渲染內(nèi)容
render() {
const { students } = this.state;
// 分?jǐn)?shù)大于100的人進(jìn)行展示
const filterStudents = students.filter((item) => item.score > 100);
// 分?jǐn)?shù)大于100,只展示兩個(gè)人的信息
const sliceStudents = filterStudents.slice(0, 2);
// 鏈?zhǔn)秸{(diào)用
// const mapStudents = students
// .filter((item) => item.score > 100)
// .slice(0, 2)
// .map((item) => {
// // TODO
// });
return (
<div>
<h2>學(xué)生列表數(shù)據(jù)</h2>
<div className="list">
{sliceStudents.map((item) => {
return (
<div className="item" key={item.id}>
<h2>學(xué)號(hào): {item.id}</h2>
<h2>姓名: {item.name}</h2>
<h2>分?jǐn)?shù): {item.score}</h2>
</div>
);
})}
</div>
</div>
);
}
}
// 3.渲染組件
root.render(<App />);
</script>
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-499588.html
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-499588.html
到了這里,關(guān)于【前端知識(shí)】React 基礎(chǔ)鞏固(十三)——列表渲染的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!