2016-08-05 77 views

回答

0

我不認爲這將是可能的沒有一些麻煩。在對話框渲染函數中,這個eventlistener被渲染,並且沒有可以覆蓋這個的道具。

{open && 
    <EventListener 
     target="window" 
     onKeyUp={this.handleKeyUp} 
     onResize={this.handleResize} 
    /> 
} 

其中調用此方法。

handleKeyUp = (event) => { 
    if (keycode(event) === 'esc') { 
     this.requestClose(false); 
    } 
}; 

source

但是,您可以潛入在node_modules /材料的UI /對話框/ dialog.js,並刪除代碼或改變它。刪除此行將阻止它關閉esc,但會計入所有對話框。也許在那之後,你可以在你自己的類中實現一個keycode事件監聽器來處理模態的關閉。

if ((0, _keycode2.default)(event) === 'esc') { 
    _this2.requestClose(false); 
} 

編輯:可能的解決方案。

我創建了2個組件,一個DialogContainer類組件和一個對話框功能組件。要使用此功能,您必須登錄npm install --save react-event-listener

爲此,您仍然需要從node_modules中刪除上述代碼。

當只有一個對話框打開時,它會在單擊esc時關閉該對話框。如果打開兩個對話框,它將首先關閉對話框2並打開對話框1。

DialogContainer.js

import React, { Component } from 'react'; 
import Dialog from './Dialog'; 
import RaisedButton from 'material-ui/RaisedButton'; 
import EventListener from 'react-event-listener'; 

export default class DialogContainer extends Component { 
    state = { 
    openDialog1: false, 
    openDialog2: false 
    }; 

    handleDialog1Open =() => { 
    this.setState({ openDialog1: true }); 
    }; 

    handleDialog2Open =() => { 
    this.setState({ openDialog2: true }); 
    }; 

    handleDialog1Close =() => { 
    this.setState({ openDialog1: false }); 
    }; 

    handleDialog2Close =() => { 
    this.setState({ openDialog2: false }); 
    }; 

    handleKeyUp = (event) => { 
    // 27 = esc 
    if (event.keyCode === 27) { 
     if (this.state.openDialog1 && this.state.openDialog2) { 
     this.handleDialog2Close(); 
     } else { 
     this.handleDialog1Close(); 
     this.handleDialog2Close(); 
     } 
    } 
    }; 

    render() { 
    return (
    <div> 
     {(this.state.openDialog1 || this.state.openDialog2) && 
     <EventListener 
     target="window" 
     onKeyUp={this.handleKeyUp} 
     />} 
     <RaisedButton label="Open1" onTouchTap={this.handleDialog1Open}/> 
     <RaisedButton label="Open2" onTouchTap={this.handleDialog2Open}/> 
     <Dialog 
     openOtherDialog={this.handleDialog2Open} 
     open={this.state.openDialog1} 
     handleClose={this.handleDialog1Close} 
     number={1}/> 
     <Dialog 
     open={this.state.openDialog2} 
     handleClose={this.handleDialog2Close} 
     number={2}/> 
    </div> 
    ) 
    } 
}; 

Dialog.js

import React from 'react'; 
import Dialog from 'material-ui/Dialog'; 
import RaisedButton from 'material-ui/RaisedButton'; 

const DialogCustom = ({ open, handleClose, number, openOtherDialog}) => { 
    return (
    <div> 
    <Dialog 
     title="Dialog" 
     modal={false} 
     open={open} 
     onRequestClose={handleClose} 
    > 
     {`this is dialog ${number}`} 
     {openOtherDialog && 
     <RaisedButton label="Open2" onTouchTap={openOtherDialog}/> 
     } 
    </Dialog> 
    </div> 
); 
}; 

export default DialogCustom; 
+0

非常感謝這個! –