我正在尝试在我的react项目中创建简单的wysiwyg编辑器,但无法正常工作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>

09-20 15:32