【问题标题】:How to set/modify value of a contenteditable div?如何设置/修改 contenteditable div 的值?
【发布时间】:2018-07-31 02:55:14
【问题描述】:

我有什么:

  • contentEditable div

  • 反应

我想要什么:

  • 给定特定的文本输入(在 contenteditable div 中),我想用图像替换文本。例如,如果有人输入“鸡”,然后输入一个空格,我假设将文本的“鸡”部分替换为一个鸡表情符号。

【问题讨论】:

    标签: javascript html reactjs contenteditable


    【解决方案1】:

    Contenteditable 是一件棘手的事情,所以我建议你使用react-contenteditableprevent caret jumps,加上一个简单的替换(你可以使用任何你想要的东西,即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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-13
      • 2021-08-28
      • 2011-02-21
      • 2023-03-29
      • 2018-05-06
      相关资源
      最近更新 更多