将 props 传递给每个组件 [英] Pass props to every component

查看:37
本文介绍了将 props 传递给每个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 React Router 在一个类内部渲染一堆路由,我需要组件能够访问触发渲染的类的实例,因为它将包含一个服务工厂的实例等.

I'm rendering a bunch of routes via a React Router, inside of a class and I need the components to have access to the instance of the class that is firing the render as it will contain an instance of a service factory etc.

然而,我找不到任何关于将 props 传递给通过 React Router 渲染的组件的信息,或者对我更有帮助的信息,将 props 传递给通过 React Router 渲染的每个组件,以便他们可以使用.

However, I cannot find any information on passing props down to components rendered via React Router or more helpful for me, passing a prop down to every component rendered via React Router so they have it available for use.

这可能吗?如果是这样,如何?

Is this possible? If so, how?

我的代码的精简版:

var routes = {
  component : 'div',
  childRoutes : [{
    path      : '/',
    component : AppContainer
  }]
};

// Not a React Component. Need a value from here, to 
// be passed to the AppContainer
class App {
  render() {
   let foo = 'bar';

    ReactDom.render(
      <Router history={history}
              routes={routes} />,
      document.getElementById('container')
    );
  }
}

// Rendered via React Router
class AppContainer extends React.Component {
  render() {
    console.log(this.props.foo); //bar
    return <div>{this.props.foo}</div>;
  }
}

推荐答案

如果你有一个根路由组件,你可以考虑一个非常简单的选项:

If you have a root route component, you could consider a very simple option like this:

export default React.createClass({
    render: function() {
      return React.cloneElement(this.props.children, { propValue: someValueHere });
    }
});

除了创建你给它的子组件,同时传递一些你选择的额外道具之外,它实际上什么都不做.它可能不会永远是您的解决方案,但我希望它足以让您开始.

That effectively does nothing other than create the child components you give it while also passing on some extra props of your choosing. It might not be your solution forever, but it's enough to get you started I hope.

这篇关于将 props 传递给每个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆