效果: 代码:
// 点击变量添加
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>
标签:const,变量,删除,文本框,inputValue,input,startPos,newValue,endPos From: https://www.cnblogs.com/shellon/p/18323682