如何使用react-router

时间:2016-06-09 12:12:57

标签: javascript reactjs react-router

这是一个 noob 问题。我正在使用 react-isomorphic-starterkit 样板(https://github.com/RickWong/react-isomorphic-starterkit)开发通用反应应用程序。我会创建一个"固定"左侧的侧栏包含指向右侧主容器的子级上呈现的其他页面的链接。这是我的代码:

routes.js

module.exports = (
    <Router history={browserHistory}>
        <Route path="/" component={Main}>
            <Route path='/inbox' component={Inbox} />
        </Route>
    </Router>
);

Main.js

export default class Main extends React.Component {
    constructor(props, context){
        super(props,context);
        console.log('Main props', props);
        console.log('Main context', props);
    }
    /**
     * componentWillMount() runs on server and client.
     */
    componentWillMount () {
        if (__SERVER__) {
            console.log("Hello server");
        }

        if (__CLIENT__) {
            console.log("Hello client");
        }
    }

    /**
     * Runs on server and client.
     */
    render () {
        return (
                <App/>
        )
    }
}

App.js

class App extends React.Component{

  constructor(props, context) {
    super(props, context);
    console.log('App props ', props);
  }

  render(){
    return (
      <div>
          <Sidebar/>
          <RightContent />
      </div>
    )
  }

}

RightContent.js

class RightContent extends React.Component{
  render(){
    return (
      <div id="b" style={{backgroundColor:"#EEF0F4", width:"100%"}}>
        <NavBar />
        {this.props.children}
      </div>
    )
  }
}

问题是:当我点击带有<div>标记的侧栏时,收件箱组件(简单的<Link to="...">)无法呈现。我不知道以下事情是否正确:正如您所看到的,在App.js类构造函数中打印props变量...但输出为undefined。但是,在Main.js道具中打印正确。 react-router版本大于2.任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您没有将道具传递给App,因此除非您使用位置背景,否则它不会拥有它们。

你应该......

render () {
  return (
    <App {...this.props}/>
  )
}

然后,您应该可以访问this.props.children中的App来呈现嵌套路由。您还需要在RightContent中指定...

render(){
  return (
    <div>
      <Sidebar/>
      <RightContent>
        {this.props.children}
      </RightContent>
    </div>
  )
}

请参阅文档中的教程... https://github.com/reactjs/react-router/blob/master/docs/Introduction.md#with-react-router

相关问题