React 列表 & Keys
React笔记
元素变量
<body> <div id="example"></div> <script type="text/babel"> function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => <li key={number.toString()}> {number} </li> ); return ( <ul>{listItems}</ul> ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('example') ); </script> </body>
|
查看效果
Keys
<body> <div id="example"></div>
<script type="text/babel"> function ListItem(props) { {} return <li>{props.value}</li>; }
function NumberList(props) { const numbers = props.numbers; {} const listItems = numbers.map((number) => {} <ListItem key={number.toString()} value={number} /> ); return ( <ul> {listItems} </ul> ); }
const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('example') ); </script> </body>
|
查看效果
用keys提取组件
<body> <div id="example"></div>
<script type="text/babel"> function ListItem(props) { return <li>{props.value}</li>; }
function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => <ListItem key={number.toString()} value={number} /> ); return ( <ul> {listItems} </ul> ); }
const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('example') ); </script> </body>
|
查看效果
在 jsx 中嵌入 map()
<body> <div id="example"></div>
<script type="text/babel"> function ListItem(props) { return <li>{props.value}</li>; }
function NumberList(props) { const numbers = props.numbers; return ( <ul> {numbers.map((number) => <ListItem key={number.toString()} value={number} /> )} </ul> ); }
const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('example') ); </script> </body>
|
查看效果
作者: 我叫史迪奇
本文来自于:
https://sdq3.link/React-list-keys.html博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议