react/antd实现textarea获取光标位置在光标处插入文字
1.首先将textarea对象通过refs存起来
<TextArea
ref={(input) => this.contentProps = input}
placeholder="请输入"
style={{ width:'600px' }}
autosize={{ minRows: 4, maxRows: 8 }}
/>
2.通过textarea组件对象拿到实例对象
let props = this.contentProps.textAreaRef;//获取dom节点实例
3.获取光标位置/控制光标位置
const getPositionForTextArea=(ctrl)=> {
let CaretPos = {
start:0,
end:0
};
if (ctrl.selectionStart) {// Firefox support
CaretPos.start = ctrl.selectionStart;
}
if(ctrl.selectionEnd){
CaretPos.end = ctrl.selectionEnd
}
return (CaretPos);
}
const position = getPositionForTextArea(props);//获取光标位置
//------------------------------------控制光标位置----------------------------------
//设置文本光标位置
const setCursorPosition =(ctrl, pos)=> {
ctrl.focus();
ctrl.setSelectionRange(pos, pos);
}
setFieldsValue({//对组件赋值 即在光标处插入文字
content : startStr+value+endStr
})
/* 这里需要注意 通过观察 setFieldsValue方法是异步的
* 就会发生光标还没插入文字呢 就已经把光标插入后的位置提前定位 所以我timeout延迟0.2秒
*/
setTimeout(function () {//overPosition就是光标的位置 比如 12|345 光标就在2
setCursorPosition(props, overPosition)
}, 200);