我的代码中有父孙子依赖。主要元素是App.js
import React from 'react'
import ReactDOM from 'react-dom'
import {ExpenseApp} from './expense-app.js'
import {Switch, BrowserRouter, Route} from 'react-router-dom'
import {FullBlog} from './FullBlog.js'
class App extends React.Component{
render(){
return(
<BrowserRouter>
<Route path='/' component={ExpenseApp}/>
<Route path='/fullblog' component={FullBlog}/>
</BrowserRouter>
)
}
}
ReactDOM.render(<ExpenseApp data={data}/>, document.getElementById('container'))
expenseapp.js有一个按钮,我想通过它来加载另一个页面
import React from 'react';
import ReactDom from 'react-dom' ;
import $ from 'jquery' ;
//import data from '../data.json';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router';
import {FullBlog} from './FullBlog.js';
import {Author} from './Author.js'
class ExpenseApp extends React.Component{
constructor(props){
super(props);
this.state={
data:this.props.data,
list:[]
}
}
render(){
var data=this.state.data;
var list=this.state.list;
var len= Object.keys(data).length;
for(var i=0;i<len;i++){
//console.log(data[i]);
list.push(<Author key={i} i={i} data={data[i]}/>);
}
return(
<div>
{list}
</div>
)
}
}
module.exports={
ExpenseApp:ExpenseApp
}
Author.js就像这样
import React from 'react';
import ReactDom from 'react-dom' ;
import $ from 'jquery' ;
//import data from '../data.json';
import { Router, Route, Link, IndexRoute, hashHistory, browserHistory } from 'react-router';
import {FullBlog} from './FullBlog.js'
class Author extends React.Component{
constructor(props){
super(props);
this.state={
data:this.props.data,
load:false,
content:'',
Author:'',
Book:''
}
this.loadBlog=this.loadBlog.bind(this);
}
loadBlog(i){
var that=this;
var data=this.state.data[i];
that.setState({
// load:true,
Content:this.props.data.Content,
})
that.context.Router.transitionTo(null,'/fullblog');
}
render(){
if(this.state.load===false){
return(
<div onClick={this.loadBlog} >
<div>{this.props.data.Author}</div>
<div>{this.props.data.Book}</div>
</div>
)
}//else{
// return(<Link to="/fullblog"><FullBlog data={this.state.data}/></Link>)
// }
}
}
Author.contextTypes = {
Router: function contextType() {
return React.PropTypes.func.isRequired;
}
};
module.exports={
Author:Author
}
然后是FullBlog.js
class FullBlog extends React.Component{
render(){
return(<div>Hello world</div>)
}
}
module.exports={
FullBlog:FullBlog
}
答案 0 :(得分:0)
您应该使用反应路由器withRouter()
更高阶函数。您传入了组件,withRouter
将router
对象添加到组件道具中。
import { withRouter } from 'react-router-dom';
// ...
export default withRouter(Author)
然后你打电话给Router.transitionTo
this.props.router.history.push('/somepath')
(我不确定那是什么)