當按鈕負責顯示模式時,我想要重定向到註冊或登錄路由。在父組件中有一個showModal函數,即作爲prop傳遞給子組件(Nav)的App。由於我負責處理onClick事件的showModal函數在App組件中,我試圖在那裏使用路由器上下文,但是我得到undefined
。無法使用路由器上下文[react-router v4]
這裏是我的代碼
index.js
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<ConnectedIntlProvider>
<Router>
<App />
</Router>
</ConnectedIntlProvider>
</Provider>
, document.querySelector('.app'));
class App extends Component {
constructor(props, context) {
super(props, context);
console.log('context', context);
this.state = { show: false };
}
showModal(e) {
e.preventDefault();
this.setState({ show: true });
this.context.router.transitionTo(e.target.href);
}
hideModal() {
this.setState({ show: false });
}
render() {
return (
<div className="container-fluid">
<Nav
showModal={(e) => this.showModal(e)}
hideModal={() => this.hideModal()}
show={this.state.show}
onHide={() => this.hideModal()}
/>
</div>
);
}
}
App.contextTypes = {
router: React.PropTypes.object
};
const Nav = (props) => (
<div>
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" href="">
<img
alt="Brand"
className="img-responsive"
src={logo}
role="presentation"
/>
</a>
</div>
<div className="collapse navbar-collapse" id="collapse-1">
<ul className="nav navbar-nav navbar-right nav-social-icon">
<li className="dropdown">
<a
href=""
className="dropdown-toggle"
data-toggle="dropdown"
>
ES
<span className="caret" />
</a>
<ul className="dropdown-menu" style={{ color: '#000', fontWeight: 'bold' }}>
<li onClick={() => props.selectedLocale('en')}>
en
</li>
<li onClick={() => props.selectedLocale('es')}>
es
</li>
</ul>
</li>
<li className="btn-group regLog">
<button
className="btn btn-default"
onClick={props.showModal}
>
<Link to={{ pathname: '/signup' }}>
{props.intl.formatMessage({ id: 'nav.registration.text' }) }
</Link>
</button>
<button
onClick={props.showModal}
className="btn btn-default"
>
<Link to={{ pathname: '/login' }}>
{props.intl.formatMessage({ id: 'nav.login.text' }) }
</Link>
</button>
{props.show ?
<ModalForm
show={props.show}
onHide={props.onHide}
/> : <span />
}
</li>
</ul>
</div>
</div>
</nav>
</div>
);
class ModalForm extends Component {
render() {
const { show, onHide, intl } = this.props;
return (
<Modal
{...this.props}
show={show}
onHide={onHide}
dialogClassName="custom-modal"
>
<Modal.Header closeButton>
<Link to='/login' className="logTitle">
<Modal.Title id="contained-modal-title-lg">
{intl.formatMessage({ id: 'nav.login.text' })}
</Modal.Title>
</Link>
<Link to='/signup' className="logTitle">
<Modal.Title id="contained-modal-title-lg">
{intl.formatMessage({ id: 'nav.registration.text' })}
</Modal.Title>
</Link>
</Modal.Header>
<Modal.Body>
<Match pattern='/login' component={Login} />
<Match pattern='/signup' component={Signup} />
</Modal.Body>
</Modal>
);
}
}
我使用反應路由器V4。
對不起,我正在使用react路由器v4,並沒有必要在根組件中有一個路由器組件。 – Serenity
路由器不一定是根,但我的觀點仍然是,應該只有一個路由器在您的應用程序中。 –
我明白了。你能幫我解決嗎?我必須在App.js中使用路由器組件? – Serenity