我的主要目标是单击 Tab 按钮后将文本区域内的空格缩进特定的量。
我正在使用 React JS 和 Bootstrap。我在渲染函数中创建了一个引导文本区域,如下所示。
<textarea class="col-12 form-control-lg" id="exampleFormControlTextarea1"placeholder="Write some Lyrics" rows="50" onKeyDown={this.useTab()} value={this.state.lyrics}
onChange={e => this.setState({ lyrics : e.target.value },()=>{
this.updateSongs("Body")
})}
</textarea>
在渲染函数之外,我正在运行 useTab() 方法。
useTab(e) {
console.log(e.keyCode); //press TAB and get the keyCode
}
运行此代码时出现以下错误。
Unhandled Rejection (TypeError): Cannot read property 'keyCode' of undefined
我确实引用了以下解决方案,但仍然无法修复错误。
ReactJS handle tab character in textarea
我必须在构造函数中绑定(bind)该函数吗?我不太确定为什么该事件没有被捕获以及我在这里似乎缺少什么。
最佳答案
请遵循以下示例:
class App extends React.Component {
constructor() {
super();
this.textAreaRef = React.createRef();
this.state = {
lyrics: ""
};
}
onChange = event => {
this.setState({
lyrics: event.target.value
});
};
// Using arrow function so no need to bind 'this'
onKeyDown = event => {
// 'event.key' will return the key as a string: 'Tab'
// 'event.keyCode' will return the key code as a number: Tab = '9'
// You can use either of them
if (event.keyCode === 9) {
// Prevent the default action to not lose focus when tab
event.preventDefault();
// Get the cursor position
const { selectionStart, selectionEnd } = event.target;
// update the state
this.setState(
prevState => ({
lyrics:
prevState.lyrics.substring(0, selectionStart) +
"\t" + // '\t' = tab, size can be change by CSS
prevState.lyrics.substring(selectionEnd)
}),
// update the cursor position after the state is updated
() => {
this.textAreaRef.current.selectionStart = this.textAreaRef.current.selectionEnd =
selectionStart + 1;
}
);
}
};
render() {
return (
<div className="App">
<textarea
ref={this.textAreaRef}
className="col-12 form-control-lg"
placeholder="Write some Lyrics"
rows="50"
value={this.state.lyrics}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
/>
</div>
);
}
}
ReactDOM.render( <App /> , document.getElementById('root'))
.App {
padding: 0 .5rem;
}
/* control tab size */
textarea {
tab-size: 8;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
关于javascript - 如何在 ReactJS + Bootstrap 文本区域内创建制表符间距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61564465/