Да, это можно сделать. Вам нужно будет прослушать Command-A (или Ctrl-A в Windows) на window.document
в componentDidMount()
и выполнить программный выбор текста. Для очистки вы не слушаете в componentWillUnmount()
.
Рабочий пример здесь: http://www.webpackbin.com/41BuFVuBz
import React from 'react';
import { Dialog } from 'material-ui';
class HelloWorld extends React.Component {
constructor(props) {
super(props);
// In ES6 classes, class methods like handleKeyDown aren't automatically bound to "this"
this.handleKeyDown = this.handleKeyDown.bind(this);
}
handleKeyDown(e) {
// If the A key is pressed while CTRL or COMMAND are also being pressed
if (e.key === 'a' && (e.ctrlKey || e.metaKey)) {
// Don't perform the default action, which would select everything on page
e.preventDefault();
const win = window;
const doc = win.document;
// this.dialogBody is the div's DOM element captured in the ref={}
const element = this.dialogBody;
if (doc.body.createTextRange) { // check if this is Internet Explorer
// Select all text in "element", the IE way
var range = doc.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (win.getSelection) { // other browsers...
// Select all text in "element", the standard way
var selection = win.getSelection();
var range = doc.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
}
componentDidMount() {
// Element has been rendered, start capturing keyboard activity
window.document.addEventListener('keydown', this.handleKeyDown);
}
componnetWillUnmount() {
// Element is no longer been rendered, stop listening
window.document.removeEventListener('keydown', this.handleKeyDown);
}
render() {
return (
<div>
<p>
Some text I don't want selected.
</p>
<p>
More text I don't want selected.
</p>
<Dialog open>
// Capture a reference to the div's DOM element inside ref={...} as this.dialogBody
<div ref={(ref) => (this.dialogBody = ref)}>
<h1>Hello World!</h1>
<p>Nice day, isn't it?</p>
</div>
</Dialog>
</div>
);
}
}
export default HelloWorld;
Код, который фактически выполняет выбор текста прикован к DOM элементу можно увидеть небольшие изменения в других ответах на SO:
Select all DIV text with single mouse click
selecting all text within a div on a single left click with javascript
Select all or highlight all Text in an Element
... единственный дополнительный «трюк» зная, куда девать DOM-код манипуляции, как это в течение всего жизненного цикла React компоненты (в основном componentDidMount
, как правило, с помощью ref
, а иногда очистки необходимы в componentWillUnmount
)
Спасибо! Он работал красиво, но я тоже стараюсь учиться. Прежде чем я приму ответ и веруюсь, не возражаете ли вы кратко комментировать, как работает каждая строка? Спасибо! –
Конечно! Я просто добавил комментарии. Надеюсь, это поможет! –