是的,這可以做到。您需要在window.document
的componentDidMount()
上偵聽Command-A(或Windows上的Ctrl-A)並以編程方式執行文本選擇。對於清理,你在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操作代碼這樣的陣營組件的生命週期內(主要componentDidMount
,通常有一個ref
的幫助下,有時清理是必要在componentWillUnmount
)
謝謝!它工作得很好,但我也試圖學習。在我接受答案並贊成之前,您是否介意簡單地評論每條線的工作方式?謝謝! –
當然!我剛剛添加了評論。希望有所幫助! –