从ReactJS中的其他组件打开模态

时间:2018-06-03 19:15:16

标签: javascript reactjs

嘿我有一个关于ReactJS的问题,因为我尝试使用react-bootstrap制作模态并在另一个组件中打开它。但没有任何反应,请查看我的代码并给我一些建议。我尝试使用LoginModalonClick="LoginModal.handleShow"组件调用函数,但这没有用。

import React, { Component } from 'react';
import { 
  Popover,
  Tooltip,
  Modal
} from 'react-bootstrap';

class LoginModal extends React.Component {
  constructor(props, context){
    super(props, context);
    this.handleShow = this.handleShow.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.state = {
        show: false
    }
}
handleShow() {
    this.setState({ show: true })
}
handleClose(){
    this.setState({ show: false })
}
render() {

    return (
       <div>
          <Modal show={this.state.show} onHide={this.handleClose}>
             <Modal.Header closeButton>
               <Modal.Title>Modal Heading</Modal.Title>
             </Modal.Header>
             <Modal.Body>
               <h1>This is modal body</h1>
             </Modal.Body>
          </Modal>
        </div>
    )
  }
}
export default LoginModal

呈现的App组件

import React, { Component } from 'react';
import LoginModal from './components/Login/Login'
import {
  Navbar, 
  NavItem,
  Nav,
  Button
} from 'react-bootstrap';
import {
  BrowserRouter as Router,
  Route,
  Switch,
 } from 'react-router-dom'

class App extends Component {

render(){
    return (
      <Router>
        <div className="menu-bar">
           <LoginModal></LoginModal>
             <Navbar inverse collapseOnSelect>
               <Nav>
                 <NavItem>
                   <Button onClick={LoginModal.handleShow}>Login</Button>
                 </NavItem>
                </Nav>
              </Navbar>

                <Switch>
                    <Route exact path="/" component={Home}/>
                </Switch>
            </div>
        </Router>
    )
  }
}
export default App;

1 个答案:

答案 0 :(得分:2)

使用LoginModal关键字来引用handleShow。然后从引用中调用class App extends Component { loginModalRef = ({handleShow}) => { this.showModal = handleShow; } onLoginClick = () => { this.showModal(); } render(){ return ( <Router> <div className="menu-bar"> <LoginModal ref={this.loginModalRef} ></LoginModal> <Navbar inverse collapseOnSelect> <Nav> <NavItem> <Button onClick={this.onLoginClick}>Login</Button> </NavItem> </Nav> </Navbar> <Switch> <Route exact path="/" component={Home}/> </Switch> </div> </Router> ) } }

2102

在这里,我准备了stackblitz片段供您在线测试。 https://stackblitz.com/edit/react-bxn5kj?file=index.js