我正在使用React开发一个笔记应用程序,当我单击侧边栏中的笔记时,它会在内容区域中打开,然后在更改文本时会更新笔记状态,并使用输入区域内的当前内容来更新当前打开的笔记
我可以使用传播算子吗?
here is the full code在codeandbox上
class App extends React.Component {
constructor() {
super();
this.state = {
notesList: [
{key: 0, title: "title of first note", note: "this is the first note"},
{key: 1, title: "title of second note", note: "this is another note"}
],
inputValue: null,
currentKey: null
};
}
noteTitleClicked = value => {
this.setState({
inputValue: value.note,
currentKey: value.key
});
};
updateNoteDetails = e => {
this.setState({
inputValue: e.target.value
});
};
render() {
const notes = this.state.notesList.map(note => (
<li key={note.key} onClick={e => this.noteTitleClicked(note)}>
{note.title}
</li>
));
const inputValue = this.state.inputValue;
return (
<div className="App">
<header>Header</header>
<div className="main">
<article>
{inputValue == null ? (
""
) : (
<input
className="noteDetails"
value={this.state.inputValue}
onChange={this.updateNoteDetails}
/>
)}
</article>
<nav>
<ul>{notes}</ul>
</nav>
</div>
<footer>Footer</footer>
</div>
);
}
}
答案 0 :(得分:1)
尝试一下:
updateNoteDetails = e => {
const updated = this.state.notesList.map(n => {
if (n.key === this.state.currentKey)
return { ...n, note: e.target.value };
return n;
});
this.setState({
inputValue: e.target.value,
notesList: updated
});
};