2016-01-02 24 views
0

我正在使用ReactJS和Meteor构建Web应用程序。我正在使用构建我的应用程序的方法,其中组件分成独立的Meteor包。与不同流星包中的ReactJS组件通信

例如。我有一个呈现表格菜单的组件(使用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.... 
     } 
     }) 
    } 
}) 

回答

0

你需要有保存状态,并可以通过该道具到两个组件的父组件。在反应中,你也可以传递函数作为道具,在这种情况下,你可以将一个函数从父项传递给子项,这将触发父项的状态改变。要更改父母的状态,您可以从孩子拨打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 
    } 
}