0

      <div
        ref={ref}
        className={clsx(
          classes && classes.size,
          error && styles.error,
          styles.textarea
        )}
        data-text={placeholder}
        onInput={(e: any) => {
          const eventValue = e.target.innerText;

          const newValue = wrapper
            ? formatMessageWithParams(wrapper, { value: eventValue })
            : eventValue;

          setValue(name, newValue);
        }}
        contentEditable
        id="textarea"
        dangerouslySetInnerHTML={{ __html: value }}
      />

我想制作可编辑的富文本元素,并将在其中显示 html 字符串。我试图找出如何在 div 中呈现 html 字符串的方法 - 可以用dangerouslySetInnerHtmlprop 完成的方式,我也发现了你不能使用onChange的,你应该使用的处理程序是onInput。我有什么问题,当我输入一些东西时,它会setValue在每次按下按钮时按功能改变值,但是字段松散焦点和 carret 停留在第一行。我该如何预防?我试图通过 实现它ref.current.focus,但它不起作用,div没有autoFocus属性,我也试图通过 显示价值data-value,但是 html 然后不起作用。有没有办法防止失去对contentEditablediv 元素的关注?

https://codesandbox.io/s/determined-dawn-i75kg?file=/src/App.js

4

1 回答 1

0

useState与其使用for ,不如setValues尝试使用useRef,它不会重新渲染组件。您还可以使用onKeyDown事件来保存数据。

更新代码:

import { useRef } from "react";
import "./styles.css";

export default function App() {
  const valueRef = useRef("");

  return (
    <div className="App">
      <div
        data-text="write text here"
        className="rich-text"
        contentEditable
        onInput={(e) => {
          valueRef.current = e.target.innerHTML;
        }}
        suppressContentEditableWarning={true}
        dangerouslySetInnerHTML={{ __html: valueRef.current }}
      />
    </div>
  );
}
于 2022-01-14T15:20:07.990 回答