简体   繁体   English

将反应组分动态插入另一反应组分中

[英]Dynamically insert react components into another react component

Right now I have a sidebar that I want to use for various forms and bits of information. 现在我有一个侧边栏,我想用于各种形式和信息。 I'm using the global event system to trigger the opening of the sidebar, but I'm not sure how to inject react components into the sidebar react component. 我正在使用全局事件系统触发侧栏的打开,但我不确定如何将反应组件注入侧栏反应组件。

I started by trying this 我开始尝试这个

componentWillMount: ->
  window.toggleSidebar = (react_component)=>
    React.renderComponent(react_component(), document.getElementById('sidebar-content'))
    @toggleSidebar()

But this didn't work once all of the components are mounted because you can't call render component into an element that is inside another component. 但是,一旦安装了所有组件,这都不起作用,因为您无法将渲染组件调用到另一个组件内的元素中。

So is there an accepted way to pass any react component into another component? 那么是否有一种可以将任何反应组件传递到另一个组件的方法?

You don't actually want to pass a component instance, you want to pass the component factory and data that it can use to render the component. 您实际上并不想传递组件实例,而是希望传递组件工厂和可用于呈现组件的数据。

events.emit('sidebar-change-request', {component: Foo, props: obj, open: true});

And in the sidebar component it'd be listening to the event: 在侧边栏组件中,它会听取事件:

  getInitialState: -> component: React.DOM.div, props: {}, open: false

  # standard event emitter stuff    
  componentDidMount: -> 
    events.addListener 'sidebar-change-request', this.handleSidebarChangeRequest

  componentWillUnmount: ->
    events.removeListener 'sidebar-change-request', this.handleSidebarChangeRequest

  # simply apply the payload to state
  handleSidebarChangeRequest: (payload) ->
    this.setState payload

  # dynamically render stuff
  render: ->
    if this.state.open
       React.DOM.div {className: "sidebar"},
          this.state.component this.state.props
    else
       React.DOM.div null

If you needed to get some information back from the component renered in the sidebar, you'd pass a callback to that components via props; 如果你需要从侧边栏中的组件中获取一些信息,你可以通过props将回调传递给那些组件; or the component could emit events. 或者组件可以发出事件。

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

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