【问题标题】:Using React contextTypes with react-router将 React contextTypes 与 react-router 一起使用
【发布时间】:2015-09-21 08:24:03
【问题描述】:

我知道这是一个相当无证的功能,但由于 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能解决吗?

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

要将 props 传递给您的组件,请在创建 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 完成。

【讨论】:

  • 与@knowbody 相同的答案,因此相同的响应。创建路由器时,我无权访问请求的道具。它们基本上是在 Application 组件中创建的。使用 createElement 我无法访问这些。
  • 好的,现在我明白你的意思了。奇怪的是,我们的应用程序完全按照您的代码设置并且可以正常工作。不同的是我们使用自己的 createElement 而我们使用 react 0.14-rc1。
【解决方案2】:

你可以使用 React Router createElement

您可以轻松地将其设置为选择性地将 props 从路由器状态或您的应用程序状态传递给路由组件(如果您愿意,可以基于路由配置)。

【讨论】:

  • 是的,我已经看到了,但我仍然不知道如何使用它。您无法访问该函数中的父道具。
【解决方案3】:

你可以试试 {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);

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

【讨论】:

  • 是的,我在其他地方发现了 cloneElement。它效果最好。我只是不觉得这是一个“干净”的解决方案。
猜你喜欢
  • 2018-12-30
  • 1970-01-01
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
  • 2021-12-08
  • 2018-08-11
  • 2019-05-15
相关资源
最近更新 更多