假设我有两个组件:
class App extends Component {
insertToStory = (word) => {
// how to get the cursor position here?
}
render() {
return (
<div>
<StoryTextarea text={this.props.text} />
<Toolbar insert={this.insertToStory} />
</div>
)
)
}
StoryTextarea
包含一个文本区域,Toolbar
包含一个按钮,当单击时,我们应该在当前光标位置下的文本区域中插入一些单词。但如何获取 insertToStory
中的光标位置?或者还有其他方法来实现这个吗?
最佳答案
使用 refs 是实现这一目标的一个不错的选择。
1º 在 StoryTextArea 组件中添加一个新方法来获取光标位置。
class StoryTextArea extends React.Component{
constructor(props) {
super(props);
this.getCursorPosition = this.getCursorPosition.bind(this);
}
getCursorPosition(){
return this.refs.textarea.selectionStart;
}
render(){
return <div>
<textarea ref="textarea"/>
</div>
}
}
2° 添加对 StoryTextArea 组件的引用
<StoryTextarea ref="storyTextArea" text={this.props.text} />
3° 使用 this.refs.storyTextArea.getCursorPosition() 调用
getCursorPosition
insertToStory = (word) => {
let position = this.refs.storyTextArea.getCursorPosition();
}
关于javascript - 获取同级组件中的光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38127189/