我在React中有一个文本区,我想把它变成一个"记事本".这意味着我希望"tab"键缩进,而不是取消焦点.我看了this answer个,但我没法用它.这是我的代码:
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"键,我的光标也会出现在字符串的末尾.有人知道如何正确设置光标位置吗?