dongyun65343
2016-03-29 19:23
浏览 51
已采纳

Go中带有子元素的React-Router如何工作?

I'm trying to use react-router with a server in Go.

I did some tests but I can not do what I want.

My react components :

var App = React.createClass({
    render: function(){
        return (
            <div>
            <h2>App</h2>
            <li><Link to="/page1">Page 1</Link></li>
            <li><Link to="/page2">Page 2</Link></li>
            </div>
        )
    }
})

var Page1 = React.createClass({
    render: function(){
        return (
            <div>
            <h2>Page 1</h2>
            <li><Link to="/page2">Page 2</Link></li>
            </div>

        )
    }
})

var Page2 = React.createClass({
    render: function(){
        return (
            <div>
            <h2>Page 2</h2>
            <li><Link to="/page1">Page 1</Link></li>
            </div>

        )
    }
})

My react routing :

   ReactDOM.render((<Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="page1" component={Page1} />
      <Route path="page2" component={Page2} />
    </Route>
  </Router>), document.getElementById('app'))

my go server :

func Render(c web.C, w http.ResponseWriter, r *http.Request) {
        RenderHTMLPage(w, "index.html")
}

func main() {
        goji.Get("/page1", Render)
        goji.Get("/page2", Render)
        goji.Get("/", Render)
        goji.Serve()
    }

My problem is when i click on Link in 'App' Component, for example :

<li><Link to="/page1">Page 1</Link></li>

url changes like that

http://localhost:8000/page1

But actual component is already App and not Page1, so url changes but not component. And if i load directly url, i have the same result.

Does anyone help me ? Thank's :)

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpwu16132 2016-03-29 20:40
    已采纳

    This isn't a go question, but a react question, you need to render the App component's children in order for the other two components to display, a la this code snippet taken from the docs for React Router (https://github.com/reactjs/react-router/blob/master/docs/API.md#props-2):

    const routes = (
      <Route component={App}>
        <Route path="groups" component={Groups} />
        <Route path="users" component={Users} />
      </Route>
    )
    
    class App extends React.Component {
      render () {
        return (
          <div>
            {/* this will be either <Users> or <Groups> */}
            {this.props.children}
          </div>
        )
      }
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题