使用React在文本区域中更改光标位置

我在React中有一个文本区域,我想变成一个“记事本”。这意味着我希望“tab”键缩进而不是散焦。这是我的代码:

handleKeyDown(event) {

if (event.keyCode === 9) { // tab was pressed

event.preventDefault();

var val = this.state.scriptString,

start = event.target.selectionStart,

end = event.target.selectionEnd;

this.setState({"scriptString": val.substring(0, start) + '\t' + val.substring(end)});

// This line doesn't work. The caret position is always at the end of the line

this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1;

}

}

onScriptChange(event) {

this.setState({scriptString: event.target.value});

}

render() {

return (

<textarea rows="30" cols="100"

ref="input"

onKeyDown={this.handleKeyDown.bind(this)}

onChange={this.onScriptChange.bind(this)}

value={this.state.scriptString}/>

)

}

运行此代码时,即使我按字符串中间的“ tab”键,光标也始终出现在字符串的末尾。有谁知道如何正确设置光标位置?

回答:

您必须在状态更新 更改光标位置(setState()不会立即发生变化this.state

为此,您必须包装this.refs.input.selectionStart = this.refs.input.selectionEnd = start

+ 1;一个函数并将其作为第二个参数传递给setState(回调)。

handleKeyDown(event) {

if (event.keyCode === 9) { // tab was pressed

event.preventDefault();

var val = this.state.scriptString,

start = event.target.selectionStart,

end = event.target.selectionEnd;

this.setState(

{

"scriptString": val.substring(0, start) + '\t' + val.substring(end)

},

() => {

this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1

});

}

}

jsfiddle

以上是 使用React在文本区域中更改光标位置 的全部内容, 来源链接: utcz.com/qa/416473.html

回到顶部