为什么 document.execCommand 在 reactjs 中不起作用?

Why document.execCommand not working in reactjs?

我正在尝试在我的 React 项目中创建简单的所见即所得编辑器,但无法正常工作document.execCommand

我指的是 codepen(他们在这里使用 jQuery 库来实现点击功能)

是否可以在 reactjs 中创建简单的所见即所得编辑器?

//document.addEventListener("click", function (e) {});

    const wrapTag = (role) => {
        switch(role) {
            case 'h1':
            case 'h2':
            case 'p':
              document.execCommand('formatBlock', false, role);
              break;
            default:
              document.execCommand(role, false, null);
              break;
          }
    }

    <div onClick={ () => { wrapTag("bold") } }>bold</div>
     <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eveniet saepe nostrum aspernatur deserunt rem neque ab.</p>

您应该添加一个 event.preventDefault,以保持焦点:

    const wrapTag = (role) => {
        document.designMode = "on"
        switch(role) {
            case 'h1':
            case 'h2':
            case 'p':
              document.execCommand('formatBlock', false, role);
              break;
            default:
              document.execCommand(role, false, null);
              break;
          }
    }

    <div onClick={ () => wrapTag("bold") } onMouseDown={(event) => 
        event.preventDefault()}>bold</div>
     <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eveniet saepe nostrum aspernatur deserunt rem neque ab.</p>