插入表情(文字)到指定光标位置
2019-08-07 本文已影响0人
vinoooooo
函数代码:
faceClick(idx: number, word: string) {
let { temList } = this.state;
temList[idx] = this.insertText(
this.refs[`script-input-${idx}`],
`[${word}]`
);
this.setState({
temList: [...temList]
});
}
insertText(obj: any, str: string) {
if (document.selection) {
var sel = document.selection.createRange();
sel.text = str;
} else if (
typeof obj.selectionStart === "number" &&
typeof obj.selectionEnd === "number"
) {
var startPos = obj.selectionStart,
endPos = obj.selectionEnd,
cursorPos = startPos,
tmpStr = obj.value;
obj.value =
tmpStr.substring(0, startPos) +
str +
tmpStr.substring(endPos, tmpStr.length);
cursorPos += str.length;
obj.selectionStart = obj.selectionEnd = cursorPos;
} else {
obj.value += str;
}
return obj.value;
}
JSX
<input
type="text"
className="tem-input"
value={item}
placeholder="请输入内容"
onChange={this.TemChange.bind(
this,
index
)}
ref={`script-input-${index}`}
/>
<Face
onClick={this.faceClick.bind(
this,
index
)}
/>