1 回答

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
您將調(diào)用 onKeyDown 回調(diào)兩次,一次在文檔上,一次在應(yīng)用程序上。事件在樹上冒泡。當(dāng)textarea沒有焦點(diǎn)時(shí),onlydocument.onkeydown
被調(diào)用。當(dāng)它處于焦點(diǎn)時(shí),document.onkeydown
和 Appdiv.onkeydown
都會(huì)被調(diào)用,從而有效地取消效果(切換狀態(tài)關(guān)閉和重新打開)。
這是一個(gè)工作示例:https://codesandbox.io/s/icy-hooks-8zuy7 ?file=/src/App.js
import React from "react";
class Console extends React.Component {
? constructor(props) {
? ? super(props);
? ? this.state = {
? ? ? visible: false,
? ? ? text: ""
? ? };
? }
? print(output: string) {
? ? this.setState({
? ? ? text: this.state.text + output + "\n"
? ? });
? }
? toggleVisible() {
? ? this.setState({ visible: !this.state.visible });
? }
? render() {
? ? const footer_style = {
? ? ? display: this.state.visible ? "inline" : "none"
? ? };
? ? return (
? ? ? <footer
? ? ? ? id="console-footer"
? ? ? ? className="footer container-fluid fixed-bottom"
? ? ? ? style={footer_style}
? ? ? >
? ? ? ? <div className="row">
? ? ? ? ? <textarea id="console" className="form-control" rows={5} readOnly>
? ? ? ? ? ? {this.state.text}
? ? ? ? ? </textarea>
? ? ? ? </div>
? ? ? </footer>
? ? );
? }
}
export default class App extends React.Component {
? constructor(props) {
? ? super(props);
? ? this.console = React.createRef();
? }
? keyDown = (e) => {
? ? this.console.current.toggleVisible(); // <-- this is undefined
? };
? componentDidMount() {
? ? document.addEventListener("keydown", this.keyDown);
? }
? componentWillUnmount() {
? ? document.removeEventListener("keydown", this.keyDown);
? }
? render() {
? ? return (
? ? ? <div className="App" style={{ backgroundColor: "blueviolet" }}>
? ? ? ? enter key to toggle console
? ? ? ? <Console ref={this.console} />
? ? ? </div>
? ? );
? }
}
另外,我建議使用React 的 hooks:
export default App = () => {
? const console = React.createRef();
? const keyDown = (e) => {
? ? console.current.toggleVisible(); // <-- this is undefined
? };
? React.useEffect(() => {
? ? // bind onComponentDidMount
? ? document.addEventListener("keydown", keyDown);
? ? // unbind onComponentDidUnmount
? ? return () => document.removeEventListener("keydown", keyDown);
? });
? return (
? ? <div className="App" style={{ backgroundColor: "blueviolet" }}>
? ? ? press key to toggle console
? ? ? <Console ref={console} />
? ? </div>
? );
};
添加回答
舉報(bào)