admin管理员组文章数量:1278652
I need to insert text at caret (current cursor position) in the React-controlled textarea (like autoplete).
For vanilla textarea I used this code:
insertAtCursor: function (myField, myValue) {
// IE
if (document.selection) {
myField.focus();
var sel = document.selection.createRange();
sel.text = myValue;
}
// FF
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart; var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue + myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}
but it does not work in React. How can I do it?
I need to insert text at caret (current cursor position) in the React-controlled textarea (like autoplete).
For vanilla textarea I used this code:
insertAtCursor: function (myField, myValue) {
// IE
if (document.selection) {
myField.focus();
var sel = document.selection.createRange();
sel.text = myValue;
}
// FF
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart; var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue + myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}
but it does not work in React. How can I do it?
Share Improve this question asked Mar 14, 2014 at 16:31 wizzard0wizzard0 1,9381 gold badge16 silver badges39 bronze badges2 Answers
Reset to default 4You need to get the node, by doing this.getDOMNode()
. Depending on the rest of your code, you might need to find the textarea within that node; or refactor your textarea into its own ponent and use refs.
insertAtCursor: function (myField, myValue) {
var myField = this.getDOMNode();
// the rest of your code
}
A nicer alternative is to just determine the cursor position, and insert your new string; and store it back in your state. This is what I'd remend.
var index = getCursorPosition();
this.setState({
value: this.state.value.slice(0, index) + theNewString + this.state.value.slice(index + 1)
})
In React 15.6.1
best option is something like that:
class CursorForm extends Component {
constructor(props) {
super(props);
this.state = {value: ''};
}
handleChange = event => {
// Custom set cursor on zero text position in input text field
event.target.selectionStart = 0
event.target.selectionEnd = 0
this.setState({value: event.target.value})
}
render () {
return (
<form>
<input type="text" value={this.state.value} onChange={this.handleChange} />
</form>
)
}
}
You can get full control of cursor position by event.target.selectionStart
and event.target.selectionEnd
values without any access to real DOM tree.
本文标签: javascriptinsert at cursor in reactStack Overflow
版权声明:本文标题:javascript - insert at cursor in react - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741220085a2360802.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论