0

在过去的几周里,我一直在学习 React 以及如何将它与 Meteor 集成。我遇到的一个问题是,在使用 FlowRouter 和 ReactLayout 时,我似乎无法弄清楚如何将属性/函数从父/布局组件传递给 ReactLayout 呈现的子组件。这是我正在尝试做的一个例子:

// Layout component with function to pass
MainLayout = React.createComponent({
  functionToPass() {
  do some stuff...
  },

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

// Component to pass into main layout
DynamicComponent1 = React.createComponent({
  render() {
    return (
      <div>
        <h1>This component will change</h1>
        <button onClick={this.props.functionToPass}>Press me!</button> // property passed from layout component
      </div>
    )
  }
});

// FlowRouter
FlowRouter.route('/', {
  action() {
    ReactLayout.render(MainLayout, {
      content: <DynamicComponent1 />  // Somehow I need to pass MainLayout.functionToPass() to DynamicComponent1 here
    }
  }
});

我应该注意,我知道如何将属性传递给不会动态变化的组件——直接在 MainLayout 中渲染。然而,这不是我想要做的。非常感谢!

4

1 回答 1

0

如果您将函数作为道具传递给 DynamicComponent1,那么我相信您应该从 ReactLayout.render 调用内部将函数传递给 DynamicComponent1。

ReactLayout.render(MainLayout, {
  content: <DynamicComponent1 functionPassed={MainLayout.functionToPass} />
}

您可以通过 访问传递的函数this.props.functionPassed

这可能不是最佳实践,但至少在使用 ReactLayout 时应该可以工作。

于 2015-12-03T23:30:11.690 回答