html - ReactJS 组件文本区域未在状态更改时更新

标签 html reactjs redux textarea

我正在尝试编写一个记笔记/整理应用程序,但我遇到了一个令人沮丧的错误。

这是我的组件:

import React from 'react';

const Note = (props) => {
  let textarea, noteForm;
  if (props.note) {
    return (
      <div>
        <button onClick={() => {
          props.handleUpdateClick(props.selectedFolderId, props.selectedNoteId, textarea.value);
        }}>
          Update
        </button>
        <textarea
          defaultValue={props.note.body}
          ref={node => {textarea = node;}}
        />
      </div>
    );
  } else {
    return <div></div>;
  }
};

export default Note;

就目前而言,每当我在笔记之间切换并使用 note.body 属性中的新内容重新呈现笔记组件时,textarea 不会更改并保留前一个笔记的内容。我已经尝试对文本区域使用 value 属性而不是 defaultValue 属性,这确实解决了组件重新呈现时文本区域内容不更改的问题,但是当我这样做时,我不再能够在 textarea 字段中键入更新笔记

有没有人知道我可以允许用户在文本字段中键入以更新注释以及在呈现不同注释时更改文本区域内容的方法?

谢谢

最佳答案

问题是为你的 prop 设置值会导致组件的所有重新渲染都使用相同的 prop,因此新文本被删除。一种解决方案是将文本保留在组件的本地状态中。要同时收听 Prop 变化,您可以在收到新 Prop 时设置状态。

const Note = React.createClass({

  getInitialState() {
        return {
        text : this.props.note.body
    }
  },

  componentWillReceiveProps: function(nextProps) {
    if (typeof nextProps.note != 'undefined') {
        this.setState({text: nextProps.note.body });
    }
  },

  render() {
    if (this.props.note) {
      return (
        <div>
          <button onClick={(e) => {
            // Fire a callback that re-renders the parent.
            // render(this.textarea.value);
          }}>
            Update
          </button>
          <textarea
            onChange={e => this.setState({ text : e.target.value })}
            value={this.state.text}
            ref={node => {this.textarea = node;}}
          />
        </div>
      );
    } else {
      return <div></div>;
    }
  }
});

https://jsfiddle.net/69z2wepo/96238/

如果您使用的是 redux,您还可以对输入的更改事件触发一个操作以触发重新渲染。您可以在 reducer 中保留输入值。

关于html - ReactJS 组件文本区域未在状态更改时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41775004/

相关文章:

java - 滚动在 Internet Explorer 中不起作用

html - 文本从一个 div 泄漏到另一个

css - 内部带有固定元素的滚动容器不能在固定元素上滚动

javascript - Redux-Thunk Chaining Actions,得到一个“dispatch(...) then is not a function error

html - css,匹配菜单顶部

javascript - JQuery Mobile 自动添加奇怪的加载消息

javascript - 引导+ react : navbar toggler not working

ios - 尝试安装 react native 时出错,运行 pod install 时无法正确构建

javascript - 通过点击react-redux流程中的其他组件来触发对组件的点击

javascript - 拉取api时redux中未定义数据