reactjs this.props.history.goback 在 Android WebView 上不起作用



this.props.history.goback 在 Android WebView 上不起作用。我的代码如下:

class App extends Component {
render() {
return (
<Router>
<div className="App">
<div className="container">
<ul>
<li><Link to="/hello">Hello</Link></li>
<br />
<li><Link to="/about">About</Link></li>
<br />
<li><Link to="/books">Books</Link></li>
<br />
</ul>
<hr/>
{/* Routes will go here */}
<Route exact={true} path="/" component={Home} />
<Route path="/hello" component={Hello} />
<Route path="/about" component={About} />
<Route path="/books" component={Books} />
</div>
</div>
</Router>
);
}
}
class About extends Component{
goBack = (props) => {
alert(this.props.history.location.pathname)
this.props.history.goBack();
}
render(){
return(
<div className="jumbotron">
<h1 className="display-3">About Me</h1>
<button onClick={this.goBack.bind(this)}>React Back</button>
</div>
)
}
}

当我尝试从"关于"页面返回时,它不起作用。 其他页面(如"你好,书籍"(也有同样的问题。

1.You just need to have a module which exports history object. Then you can use it in your anywhere project
// history.js
import { createBrowserHistory } from 'history'
export default createBrowserHistory({
/* pass a configuration object here if needed */
})
//App component    
class App extends Component {
render() {
return (
<Router history={history}>
<div className="App">
<div className="container">
<ul>
<li><Link to="/hello">Hello</Link></li>
<br />
<li><Link to="/about">About</Link></li>
<br />
<li><Link to="/books">Books</Link></li>
<br />
</ul>
<hr/>
{/* Routes will go here */}
<Route exact={true} path="/" component={Home} />
<Route path="/hello" component={Hello} />
<Route path="/about" component={About} />
<Route path="/books" component={Books} />
</div>
</div>
</Router>
);
}
}
// some-other-file.js
import history from './history'
history.push('/about')

2.使用上下文接口

class About extends Component {
static contextTypes = {
router: () => true, // replace with PropTypes.object if you use them
}
render() {
return (
<button
className="button icon-left"
onClick={this.context.router.history.goBack}>
Back
</button>
)
}
}

3.与路由器一起使用高阶组件

import React from "react";
import { withRouter } from "react-router-dom";
class Home extends React.Component {
...
myFunction() {
this.props.history.goBack;
}
...
}
export default withRouter(Home);

最新更新