Приведенный ниже код представляет собой минимальный рабочий пример, объясняющий мою проблему. Этот код генерирует 3 компонента Note с помощью Array.map, и когда вы нажимаете в них Enter, он очищает статически сгенерированный компонент Note над ними, используя ссылку на его элемент DOM.
Вместо этого я хочу, чтобы заметка, которую вы нажимаете, была пустой. Я думаю, это потребует создания динамического массива, содержащего {id, ref} для каждой заметки, поэтому я мог бы передать идентификатор заметки в handleKeyDown, затем выполнить поиск в массиве refs для этого идентификатора и использовать соответствующий ref для изменения элемента DOM. Но мне сложно понять, как это сделать на самом деле.
Я понимаю, что использовать здесь refs не обязательно, но это просто пример, поскольку мой реальный код намного длиннее и вызывает focus ().
import React, { Component } from "react";
import "./App.css";
class App extends Component {
constructor() {
super();
this.notes = [
{ text: "Hello world 1", id: 1 },
{ text: "Hello world 2", id: 2 },
{ text: "Hello world 3", id: 3 }
];
this.ref = React.createRef();
}
handleKeyDown = event => {
if (event.key === "Enter") {
event.preventDefault();
this.ref.current.textContent = "";
}
};
render() {
return (
<div>
<Note
text = {"StaticNote"}
key = {0}
id = {0}
handleKeyDown = {this.handleKeyDown}
innerRef = {this.ref}
/>
{this.notes.map(note => (
<Note
text = {note.text}
key = {note.id}
id = {note.id}
handleKeyDown = {this.handleKeyDown}
/>
))}
</div>
);
}
}
class Note extends Component {
render() {
return (
<p
ref = {this.props.innerRef}
contentEditable
onKeyDown = {this.props.handleKeyDown}
>
{this.props.text}
</p>
);
}
}
export default App;



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вам необходимо сохранить отдельную ссылку для всех ваших компонентов Note, а затем передать индекс заметки в фокусе функции handleKeyDown.
import React, { Component } from "react";
import "./App.css";
class App extends Component {
constructor() {
super();
this.notes = [
{ text: "Hello world 1", id: 1, ref: React.createRef() },
{ text: "Hello world 2", id: 2, ref: React.createRef() },
{ text: "Hello world 3", id: 3, ref: React.createRef() }
];
}
handleKeyDown = (event, index) => {
if (event.key === "Enter") {
event.preventDefault();
this.notes[index].ref.current.textContent = "";
}
};
render() {
return (
<div>
<Note
text = {"StaticNote"}
key = {0}
id = {0}
handleKeyDown = {this.handleKeyDown}
innerRef = {this.ref}
/>
{this.notes.map((note, index) => (
<Note
index = {index}
innerRef = {note.ref}
text = {note.text}
key = {note.id}
id = {note.id}
handleKeyDown = {this.handleKeyDown}
/>
))}
</div>
);
}
}
class Note extends Component {
render() {
return (
<p
ref = {this.props.innerRef}
contentEditable
onKeyDown = {(e) => this.props.handleKeyDown(this.props.index)}
>
{this.props.text}
</p>
);
}
}
export default App;