点击内置变量,在文本框中插入,按下退回键或者删除键删除变量

效果:
代码:
 
 
// 点击变量添加
 const handleTagClick = (param: any) => {
   const input: any = inputRef.current.input;
   if (input) {
     const startPos = input.selectionStart;
     const endPos = input.selectionEnd;


     const newValue = `${inputValue.substring(0, startPos)}{${param.label}}${inputValue.substring(
        endPos
     )}`;


     setInputValue(newValue);
     setTimeout(() => {
        input.setSelectionRange(
          startPos + param.label.length + 2,
          startPos + param.label.length + 2
       );
        input.focus();
     }, 0);
   }
  };


  // 返回键或者删除键 删除变量
  const handleKeyDown = (e: any) => {
   if (e.key === "Backspace" || e.key === "Delete") {
     let newValue = "";


     const input: any = inputRef.current.input;
     if (input) {
       const startPos = input.selectionStart;
       const endPos = input.selectionEnd;


       if (startPos === endPos) {
         const replaceStr = inputValue.substring(0, startPos).replace(/{[^}]+}$/, "");
          newValue = `${replaceStr}${inputValue.substring(endPos)}`;
         if (newValue !== inputValue) {
           // 重置光标位置
           setTimeout(() => {
              input.setSelectionRange(replaceStr.length, replaceStr.length);
              input.focus();
           }, 0);
            e.preventDefault();
         }
       } else {
         // 选中文本后,则正常删除
          newValue = inputValue;
       }
     }
     setInputValue(newValue);
   }
  };


...
...


       <Input
          className="pdf-name-rule"
          value={inputValue}
          ref={inputRef}
          placeholder="请输入pdf简历命名"
          onChange={handleInputChange}
          onKeyDown={handleKeyDown}
       />
       <div className="variable-tip">pdf简历可插入如下变量</div>
       <div className="variable-list">
         {VariableList.map((item) => (
           <div className="variable-item" key={item.value} onClick={() => handleTagClick(item)}>
             {item.label}
           </div>
         ))}
       </div>

 

posted @ 2024-07-25 17:05  shellon  阅读(1)  评论(0编辑  收藏  举报