简体   繁体   English

如何在React中动态地在一些现有元素之间添加新元素?

[英]How do I add new elements in between some existing ones dynamically in React?

I am trying to rewrite a traditional html/js app in React. 我正在尝试在React中重写传统的html / js应用程序。 I have a React component that I want to build that will be made up of many different spans that are next to each other. 我有一个要构建的React组件,该组件将由彼此相邻的许多不同的跨度组成。

<span id="1">one</span><span id="2">two</span><span id="4">four</span>

These elements will be generated from some state. 这些元素将从某种状态生成。 The state may change in the future and new spans may need to be added or removed. 将来状态可能会发生变化,可能需要添加或删除新的跨度。 For example, the value 'three' might be introduced in the future and it will need to be placed in between some previously created elements (between 'two' and 'four'). 例如,将来可能会引入值“三”,并且需要将其放置在一些先前创建的元素之间(在“两个”和“四个”之间)。 The spans should look like this: 跨度应如下所示:

<span id="1">one</span><span id="2">two</span><span id="3">three</span><span id="4">four</span>

My question is, should I totally recreate all of the spans from my state in each call to render() every time a single small state change is made? 我的问题是,每次进行单个小的状态更改时,我是否应该在每次对render()的调用中完全重新创建状态的所有范围? Or, can I find the new element's neighbor by id and then add the new one next to it (this is how my non-react app works)? 或者,我可以按ID查找新元素的邻居,然后在其旁边添加新元素(这是我的非反应式应用程序的工作方式)吗?

The former seems like it would be a lot of work to add one new span. 前者似乎要增加一个新跨度需要大量工作。 The latter seems more efficient but I don't know if I can use document.getElementById() or something equivalent and add the new element in the more traditional html/js way. 后者似乎更有效,但是我不知道是否可以使用document.getElementById()或等效的东西并以更传统的html / js方式添加新元素。

Also, should I use React 'keys' for these spans? 另外,我应该在这些范围内使用React'keys'吗?

A very simple example: 一个非常简单的例子:

const myArr = [
  { id: 1, value: 'one' },
  { id: 2, value: 'two' },
  { id: 4, value: 'four' }
]

myArr.map(item => <span key={item.id}>{item.value}</span>)

Now if at some point you would add another object to myArr and sort it accordingly it will appear in the place you gave it by sorting. 现在,如果您要在另一个位置将另一个对象添加到myArr并对其进行相应的排序,它将出现在您通过排序指定的位置。 Only the elements with the keys which are new to the react-virtual-dom will be re-rendered, means the new object added to myArr. 只有具有对react-virtual-dom新的键的元素才会被重新渲染,这意味着将新对象添加到myArr。 The reset will stay from the last render cycle. 重置将从最后一个渲染周期开始。

So by using unique keys you give react the ability to understand which dynamic elements needs to be created, deleted or updated 因此,通过使用唯一键,您可以做出反应,从而了解需要创建,删除或更新哪些动态元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM