与不同Meteor包中的ReactJS组件进行通信

时间:2016-01-02 01:38:47

标签: meteor reactjs

我正在使用ReactJS和Meteor构建Web应用程序。我正在使用构造我的应用程序的方法,其中组件被拆分为单独的Meteor包。

例如。我有一个组件,它呈现一个表格菜单(使用semantic-ui选项卡模块)并初始化选项卡,然后每个选项卡都是自己的React组件。

我如何能够访问另一个组件中的一个组件中的DOM。

示例:

Component = React.createClass({
    componentDidMount() {
      $('.menu .item').tab({
        onVisible: () => {
          // I need to call a function here, which is defined in OtherComponent, 
          // but this jQuery won't run in OtherComponent
        }
      })
    },

    render() {
      return (
        <div className="ui tabular menu">
          <div className="active item" data-tab="tab-1">Tab 1</div>
          <div className="item" data-tab="tab-2">Tab 2</div>
        </div>

        /* more code */

        <div className="ui active tab" data-tab="tab-1"></div>
        <div className="ui tab" data-tab="tab-2"></div>
       )
    }
}

OtherComponentInDifferentPackage = React.createClass({
   componentDiMount() {
      $('.menu .item').tab({
        onVisible: () => {
           // this won't work.... 
        }
      })
   }
})

1 个答案:

答案 0 :(得分:0)

您需要拥有一个包含状态的父组件,并且可以将其作为props传递给两个组件。在反应中,您还可以将函数作为道具传递,在这种情况下,您可以将函数从父项传递给子项,这将触发父项中的状态更改。要更改父级的状态,您可以从孩子那里调用this.props.toggleVisible()

// Parent Component
toggleVisible() {
  this.setState({
    visible: !this.state.visible
  });
}
getInitialState() {
  return {
    visible: false
  }
}
render() {
  return (
    <div>
      <Component
        visible={this.state.visible}
        toggleVisible={this.toggleVisible}
      />
      <OtherComponentInDifferentPackage
        visible={this.state.visible}
        toggleVisible={this.toggleVisible}
      />
    </div>
  );
}

// Child Component
componentWillReceiveProps(nextProps) {
  if (nextProps.visible !== this.props.visible) {
    // do something
  }
}
相关问题