javascript - 更改特定索引处的 React State 数组

标签 javascript arrays reactjs object setstate

正如标题所示,我正在尝试将 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/

相关文章:

c++ - 可以将数组的子部分传递给函数吗? C++

arrays - Postgres 9.4 按 json 数组的元素值选择

css - 如何在 React 中将多个浏览器特定值添加到 CSS 样式中?

javascript - React 中的内联 CSS - 如何设置多个 li 元素的样式

javascript - 显示字段,允许按钮编辑和保存 html

javascript - 如何在 React Redux 中从组件获取事件到容器

javascript - 面向公众的 REST 身份验证机制

c - memcpy 将数组对象复制到 C 中的字符指针,反之亦然

javascript - 如何使 jQuery 代码不适用于已登录的 Wordpress 用户?

reactjs - 在 react 中添加单选按钮时遇到问题 - 输入是一个空元素标签,既不能有 `children` 也不能使用 `dangerouslySetInnerHTML`