首页 > 解决方案 > 如何设置/修改 contenteditable div 的值?

问题描述

我有的:

我想要的是:

标签: javascripthtmlreactjscontenteditable

解决方案


Contenteditable 是一件棘手的事情,所以我建议你使用react-contenteditable防止插入符号跳转,再加上一个简单的替换(你可以使用任何你想要的东西,即 regexp whatelse)可以解决问题:

import React from 'react';
import ReactDOM from 'react-dom'
import ContentEditable from 'react-contenteditable'

class MyComponent extends React.Component {
  state = { html: "Hello world" };

  handleChange = evt => {
    let html = evt.target.value

    // you could take any replacement method you want
    if (html.slice(-11, html.length) === 'chicken<br>') {
      html = `${html.slice(0, -11)} ❤ <br>`
    }

    this.setState({ html });
  };

  render = () => {
    return <ContentEditable
      html={this.state.html} // innerHTML of the editable div
      disabled={false}       // use true to disable edition
      onChange={this.handleChange} // handle innerHTML change
    />
  };
};

你可以玩它:https ://codesandbox.io/s/2x00nwnx6p


推荐阅读