react列表和keys
来源:互联网 发布:联通宽带网络测速 编辑:程序博客网 时间:2024/06/05 12:50
列表和keys
- 基础的列表组件
生成一个listItems
数组,组件返回ul
列表,渲染页面
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('root'));
Keys
- 数组中的每一项都要有固定的
key
,以便React
区分哪些元素变化(增加/修改/移除). - 它只是作为
React
自己识别,并不会传递到组件上 - 同一个数组中不能有同样的
key
const numbers = [1, 2, 3, 4, 5];const listItems = numbers.map((number) => <li key={number.toString()}> {number} </li>);
没有固定ID的时候也可以用当前项的index
代替,但是不建议这样做,因为会拖慢速度
const todoItems = todos.map((todo, index) => // Only do this if items have no stable IDs <li key={index}> {todo.text} </li>);
点击这里了解keys
的重要性
- 提升带有
key
的组件
Key
只有在数组中才有意义,想要提升ListItem
为一个组件是,需要把key
留在数组中的<LitsItem />
,而不是<li>
上
//错误示例function ListItem(props) { const value = props.value; return ( // Wrong! There is no need to specify the key here: <li key={value.toString()}> {value} </li> );}function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => // Wrong! The key should have been specified here: <ListItem value={number} /> ); return ( <ul> {listItems} </ul> );}const numbers = [1, 2, 3, 4, 5];ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('root'));
//正确示例function ListItem(props) { // Correct! There is no need to specify the key here: return <li>{props.value}</li>;}function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => // Correct! Key should be specified inside the array. <ListItem key={number.toString()} value={number} /> ); return ( <ul> {listItems} </ul> );}const numbers = [1, 2, 3, 4, 5];ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('root'));
阅读全文
0 0
- react列表和keys
- React.js 官网资料摘记:列表&keys
- React-Component-Keys
- 8.React中文之列表和键
- React官方文档--Lists and Keys
- SCAN和KEYS 区别
- react入坑之列表和key(索引)
- Keys
- keys
- keys
- keys
- Keys
- keys
- "keys": "*"
- React Native List列表
- React生成有序列表
- React生成无序列表
- react-bits:列表组件
- Autodesk.AutoCAD.Mechanical.v2016.Win32 & Win64-ISO 2DVD(2D机械设计和绘图方面的顶级工具软件
- 定位方法
- 职场社交应避免的不良心理
- Java-MVC-内省反射2-封装MyBeanUtils
- JVM中的分布式垃圾回收(DGC)
- react列表和keys
- 单例模式的实践
- windows常用命令
- Android8.0运行时权限策略变化和适配方案
- 比赛9 总结
- 初识hadoop
- VS_WinForm_IO.Ports.SerialPort串口通信初步程序代码
- iPhoneX刚发布,各界的段子手就来了,笑喷!
- eclipse快捷键