简体   繁体   English

将道具从React Router传递到服务器上的子代

[英]Passing props from react router to children on the server

I'm building an Isomorphic app using React, react-router v3 and material-ui. 我正在使用React,react-router v3和material-ui构建同构应用程序。 One of the requirements of material-ui in server-side rendering is to pass to the theme the client's user agent, so MUI will be able to prefix their inline styles accordingly. 服务器端渲染中Material-ui的要求之一是将主题传递给客户端的用户代理,因此MUI将能够相应地为其内联样式添加前缀。

Originally the root component of the app was the router, ie on the server side: 最初,应用程序的根组件是路由器,即在服务器端:

<RouterContext {...renderProps}/>

And on the client: 在客户端上:

<Router children={routes} history={browserHistory} />

Now, since I didn't know how to pass the user agent to the RouterContext on the server, I came up with an (ugly?) solution: I've created a useless component named Root, to whom I passed the user agent, and Root had the router as his children , ie on the server side: 现在,由于我不知道如何将用户代理传递给服务器上的RouterContext ,所以我想出了一个(丑陋的)解决方案:我创建了一个名为Root的无用组件,将用户代理传递给了该组件, Root将路由器作为他的children ,即在服务器端:

<Root userAgent={userAgent}>
  <RouterContext {...renderProps}/>
</Root>

and on the client: 并在客户端上:

<Root>
  <Router children={routes} history={browserHistory} />
</Root>

Now, everything works well but I don't really like creating that useless element if I don't have to, so my question is - is there a better way? 现在,一切正常,但是如果不需要,我真的不喜欢创建那个无用的元素,所以我的问题是-有更好的方法吗?

Can I somehow pass the user agent to RouterContext on the server, which will in turn pass it to the Index Route which will create the theme? 我可以通过某种方式将用户代理传递给服务器上的RouterContext ,后者又将其传递给创建主题的索引路由吗?

Here's the code of Root if someone's interested: 如果有人感兴趣,这是Root的代码:

class Root extends React.Component {
  constructor(props){
    super();
    this.muiTheme = getMuiTheme(customTheme, { userAgent: props.userAgent });
  }

  render () {
    return (
    <MuiThemeProvider muiTheme={this.muiTheme}>
      {this.props.children}
    </MuiThemeProvider>
    );
  }
}

You can use createElement on RouterContext to achieve this. 您可以在RouterContext上使用createElement实现此目的。

<RouterContext
  {...renderProps}
  createElement={(Component, props) => <Component {...props} userAgent={data.userAgent} />}
/>

This will make userAgent available in the props of all route components. 这将使userAgent在所有路由组件的props中可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM