我正在尝试在REACTJS中的onclick事件上隐藏和显示路由器组件。但是找不到我可以做到的方式。 这是我的代码-
import React from 'react';
import { BrowserRouter as Router,Route, Link, Switch} from 'react-router-dom';
import SignIn from './SignIn'
export default class Clicksigningin extends React.Component{
render(){
return(
<div>
<Router>
<div>
<Link to={'/SignIn'}><button className='btn btn-danger'>Sign In</button></Link>
<Switch>
<Route exact path = '/SignIn' component = {SignIn} />
</Switch>
</div>
</Router>
</div>
)
}
}
答案 0 :(得分:0)
更好的方法是删除此特定组件的路由器。 在单个组件(例如SignIn)中,您可以具有一个按钮,该按钮将切换(显示/隐藏)signIn部分。
import React from 'react';
import { BrowserRouter as Router,Route, Link, Switch} from 'react-router-dom';
import SignIn from './SignIn'
export default class Clicksigningin extends React.Component{
constructor(props){
super(props);
this.state={showSignInPage:false}
}
toggleSignIn(){
this.setState({showSignInPage:!this.state.showSignInPage});
}
render(){
return(
<div>
{this.state.showSignInPage && <SignIn/>}
<button className='btn btn-danger' onClick={()=>this.toggleSignIn()}>Sign In</button>
</div>
</Router>
</div>
)
}
PS:我尚未测试过的代码。
答案 1 :(得分:0)
您可以通过这种方式
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from "react-router-dom";
function SignIn() {
return "hello";
}
class App extends React.Component {
state = {
current: ""
};
toggle = () => {
this.setState({ current: this.state.current==''?"SignIn":"" })
};
render() {
return (
<Router>
<div>
{this.state.current == "SignIn" ? (
<Redirect to="/SignIn" />
) : (
<Redirect to="" />
)}
<button className="btn btn-danger" onClick={this.toggle}>
Sign In
</button>
<Switch>
<Route exact path="/SignIn" component={SignIn} />
</Switch>
</div>
</Router>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);