首页 > 解决方案 > React 只重新渲染修改过的 contenteditable 一次

问题描述

重现这有点奇怪,不得不使用超时来破解它,但它确实模拟了我遇到的问题。

https://jsfiddle.net/mwqyub1v/13/

1) React 渲染divwith abc123操作这个字符串(添加一个4什么的)

2) 在第一次超时之后,React 将删除内容——现在在第二个计时器触发之前手动在框中输入一些内容。.

3) 在第二个计时器上,React确实使用as运行该render方法(注意日志记录),但 div 没有更新(它不会删除您在 abc123 消失后输入的任何文本)。this.props.valuenull

我知道玩 contenteditable 的内容会阻止 React 管理该内容(因此我取消了警告)。但是,为什么我在上面的步骤 1 中修改了文本后组件会正确更新?此外,如果第二个计时器设置value为其他文本,而不是null,则组件再次正确更新。

我怎样才能让这个组件始终重置 contenteditable 内容,即使值是null

标签: javascriptreactjsrenderingcontenteditable

解决方案


之所以没有更新第二次超时,是因为虚拟 dom 没有检测到任何差异。这将根据以下内容设置 innerHTML propshttps ://jsfiddle.net/mwqyub1v/35/ 。

class App extends React.Component {

  componentDidMount() {
    this.node = React.findDOMNode(this);
  }

  componentDidUpdate() {
    this.node.innerHTML = this.props.value;
  }

  render() {

    console.log('value', this.props.value);

    return React.createElement('div', {
        contentEditable : true,
      suppressContentEditableWarning : true
    }, this.props.value);

  }

}

推荐阅读