通过 React 中的 contentEditable 更改后从 div 获取 innerHTML

getting innerHTML from a div after changes through contentEditable in React

感谢您抽出宝贵时间查看此内容。

我正在努力寻找如何在 React 中专门使这项工作。

我使用 contentEditable 使 div 元素可编辑,然后我使用 Refs 使 div 引用其 innerHTML。但是信息好像没有放入状态body

最终目的是把它保存在数据库中,然后加载替换div。

代码:

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

export default function App() {

let  myRef= useRef()
  const [body, setBody] = useState("");

  let click = () => {
    setBody(myRef.innerHTML)
  }


  return (
    <div className="App">
      <h1 ref={myRef}>Hello CodeSandbox</h1>
      <div></div>
      <h1 contentEditable={true}> rewrite me!</h1>
      <button onClick={click}> CLICK!</button>
    <h1>{body}</h1>

    </div>
  );
}

沙盒

https://codesandbox.io/s/wispy-glitter-nfym4?file=/src/App.js

使用 myRef.current.innerHTML 访问 innerHTML

来自docs

When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

<div id="root"></div>    
<script type="text/babel">
function App() {
  let myRef = React.useRef();
  const [body, setBody] = React.useState("");

  let click = () => {
    setBody(myRef.current.innerHTML);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div></div>

      {/* I think you misassigned your `myRef`, shouldn't it be on this h1? */}
      {/* suppressContentEditableWarning=true, to suppress warning */}
      <h1 ref={myRef} contentEditable={true} suppressContentEditableWarning={true}> rewrite me!</h1>

      <button onClick={click}> CLICK!</button>
      <h1>{body}</h1>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
</script>