javascript - 如何设置/修改 contenteditable div 的值?
问题描述
我有的:
内容可编辑的 div
反应
我想要的是:
- 给定某个文本输入(在 contenteditable div 中),我想用图像替换文本。例如,如果有人输入“鸡”然后输入一个空格,我假设将文本的“鸡”部分替换为一个鸡表情符号。
解决方案
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
/>
};
};
推荐阅读
- c - system() 命令没有检测到我想要的扩展名。程序检测到“设置路径”但无法找到路径
- flutter - Flutter:将值通知器数据上传到 Firebase
- vue.js - 赛普拉斯没有针对和更改 Vuetify v-data-table 组件的“每页行数”
- c++ - CLION:如何从 C++ 源代码生成类图
- reactjs - 为什么防止默认不起作用?handleSubmit 已绑定并且传播不起作用
- android - 高尔夫记分卡界面的最佳布局/容器是什么?
- apache-kafka - 不使用 Kafka Connect 复制架构更改
- r - R代码仅将列从日期时间更改为时间
- django - 我从贝宝获取账单时遇到问题
- javascript - 用 Vite 将 JS 和 CSS 打包成一个文件