开发手册 欢迎您!
软件开发者资料库

ReactJS - Keys

ReactJS Keys - 从简单和简单的步骤学习ReactJS,从基本到高级概念,包括概述,环境设置,JSX,组件,状态,道具概述,道具验证,组件API,组件生命周期,表单,事件,参考,键,路由器,磁通概念,使用磁通,动画,服务器端渲染,高阶组件,最佳实践。

在使用动态创建的组件或用户更改列表时,

React 非常有用.设置值将使您的组件在更改后唯一标识.

使用键

让我们动态创建内容具有唯一索引(i)的元素. map 函数将从 data 数组中创建三个元素.由于值对于每个元素都必须是唯一的,因此我们将i指定为每个创建元素的键.

App.jsx

import React from 'react';class App extends React.Component {   constructor() {      super();      this.state = {         data:[            {               component: 'First...',               id: 1            },            {               component: 'Second...',               id: 2            },            {               component: 'Third...',               id: 3            }         ]      }   }   render() {      return (         
            
               {this.state.data.map((dynamicComponent, i) => )}            
         
      );   }}class Content extends React.Component {   render() {      return (         
            
{this.props.componentData.component}
            
{this.props.componentData.id}
         
      );   }}export default App;

main.js

import React from 'react';import ReactDOM from 'react-dom';import App from './App.jsx';ReactDOM.render(, document.getElementById('app'));

我们将得到以下每个元素的Key值的结果.

React Keys示例

如果我们将来添加或删除某些元素或更改动态创建的元素的顺序,React将使用值用于跟踪每个元素.