使用ReactJs中的按钮在组件之间导航和路由
每当单击“发送问题”按钮时,我都会尝试导航到另一个组件 这是我的尝试:使用ReactJs中的按钮在组件之间导航和路由,reactjs,react-router,Reactjs,React Router,每当单击“发送问题”按钮时,我都会尝试导航到另一个组件 这是我的尝试: <p> {(this.state.hide) && ( <button style={{ background: "green", color: "white" }} onClick={()=> {this.props.history.replace('/questions')}} > Send Question
<p>
{(this.state.hide) && (
<button
style={{ background: "green", color: "white" }}
onClick={()=> {this.props.history.replace('/questions')}}
>
Send Question
</button>
)}
</p>
以下是我与路由相关的导入
import { Route } from 'react-router';
import { withRouter } from 'react-router-dom';
import { BrowserRouter as Router } from 'react-router-dom'
很可能您没有使用路由器包装组件
class YourComponent extends React.Component {
render() {
return (
...
<button onClick={() => this.props.history.replace('/questions')}>
...
);
}
}
export default withRouter(YourComponent);
class YourComponent扩展了React.Component{
render(){
返回(
...
this.props.history.replace('/questions')}>
...
);
}
}
使用路由器导出默认值(您的组件);
另一个简单的解决方案,您不需要在路由器上使用
class YourComponent extends React.Component {
render() {
return (
...
<button onClick={() => this.props.history.replace('/questions')}>
...
);
}
}
export default withRouter(YourComponent);
import*as React from'React';
从'react router dom'导入{Link};
导出默认组件扩展React.Component{
render(){
返回(
...
{this.state.hide&&(
发送问题
)}
...
);
}
}
另请注意:如果您想替换当前URL,您应该使用this.props.history.replace,但如果您想将用户导航到新页面(这是您最有可能要做的。您应该使用this.props.history.push)
也许只是像这样使用from react router dom并在路由器中声明路由?@davidbucka我想使用按钮而不是链接
import * as React from 'react';
import { Link } from 'react-router-dom';
export default YourComponent extends React.Component {
render() {
return (
...
<p>
{ this.state.hide && (
<Link to="/questions">
<button
style={{ background: "green", color: "white" }}
>
Send Question
</button>
</Link>
)}
</p>
...
);
}
}