正如标题所示,我正在尝试将 state object
内的数组作为目标但如果你尝试过的话你就会猜到。这并不像听起来那么简单。我在这里查看了几个问题( React: How do I update state.item[1] on setState? (with JSFiddle) 和 ReactJS - setState of Object key in Array ),但都没有解决我的问题。
我需要的是针对 noteData
内的特定索引数组,并根据用户在 <TextArea />
中输入的内容来更新它成分。不太清楚为什么,但我的 noteData
数组只是读取为带有空字符串的数组 noteData = ['']
.
如果需要更深入的了解,可以前往https://stackblitz.com/edit/note-taking并 fork 页面并自行编辑。至少可以说,文件结构很愚蠢。我开始使用 redux,但中途决定不使用它。
状态和函数TextArea
class NoteList extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
noteName: [],
noteData: [],
selectedNote: []
}
}
handleInputValue(e) {
this.setState({
inputValue: e.target.value
});
}
addNoteFunc(e) {
this.setState({
noteName: [ ...this.state.noteName, e.target.value ],
noteData: [ ...this.state.noteData, '' ]
});
}
// everytime the user types, change the value of noteData
handleNoteData(e, index = this.state.selectedNote[0]) {
const copyNoteData = Object.assign({}, this.state);
copyNoteData.noteData[index] = e.target.value;
this.setState(copyNoteData);
}
handleSelectedNote(index) {
this.setState({
selectedNote: [ index ]
});
}
<textarea
value={this.state.noteData[this.state.selectedNote[0]]}
handleNoteData={(e, index) => this.handleNoteData(e, index)}
/>
实际的 TextArea 组件
import React from 'react';
const TextArea = props => {
return (
<div className='textarea'>
<textarea
value={props.value}
onKeyDown={props.handleNoteData}
/>
</div>
);
}
export default TextArea;
最佳答案
你的代码有错误,因为textarea不是正确的组件,它应该是TextArea而不是textarea,它是一个html元素,你首先必须在notelist.js中导入它,这就是为什么onKeyDown props是未设置。
<TextArea
value={this.state.noteData[this.state.selectedNote[0]]}
handleNoteData={(e, index) => this.handleNoteData(e, index = this.state.selectedNote[0])}
/>
此外,您必须将handleNoteData添加到onChange事件,否则在onKeyDown事件中texarea值将永远不会改变,因为您每次都将其重置为e.target.value。
试试这个: https://stackblitz.com/edit/note-taking-y5hwsb?file=containers/notelist.js
关于javascript - 更改特定索引处的 React State 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46652274/