将 React contextTypes 与 react-router 一起使用

Using React contextTypes with react-router

我知道这是一个相当未记录的功能,但由于 react-router 没有将道具传递给子路由组件的干净方式,我想使用上下文。

<Router history={history}>
    <Route component={Application} path="/(:id)">
        <IndexRoute component={EditDocument} />
    </Route>
</Router>

class Application extends Component {

    static childContextTypes = {
        charts: PT.array.isRequired,
    }

    getChildContext() {
        return { charts: this.getCharts() };
    }

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

class EditDocument extends Component {

    static contextTypes = {
        charts: PT.array.isRequired,
    }

    componentWillMount() {
        this.context.charts === undefined
    }
}

我目前使用的是 React 0.13。这可以用 0.14 解决吗?

你可以使用 React Router createElement

You can easily set it up to selectively pass props from router state or your app state to route components (based on route config if you want to).

要将道具传递给您的组件,您需要在创建 Router:

之前覆盖 RoutercreateElement 方法
const createElement = function(Component, props) {
   return <Component {...props} myProps={{your: 'props'}} />;
 };

<Router history={history} createElement={createElement}>
    <Route component={Application} path="/(:id)">
        <IndexRoute component={EditDocument} />
    </Route>
</Router>

这个方法对我们有用。可以在服务器上使用 RoutingContext.

完成相同的操作

你可以试试{React.cloneElement(this.props.children, {someExtraProp: something })}

所以你将额外的东西传递给你的视图

例如

function renderApp(data) {

var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;

var App = React.createClass({

render: function () {

  return (

<AppShell>

        {React.cloneElement(this.props.children, {data:data})}

    </AppShell>
  );
}
});

var rootRoute = {
component: 'div',
childRoutes: [{
path: '/',
component: {App},
///etc
}]
};

React.render(

React.render(

 <Router routes={rootRoute}/>,
document.body

);

,
document.body
);

}
renderApp(data);

希望that.s有用,如果我需要更好地解释,请告诉我