2017-06-21 65 views
3

我有下面的類時獲取從一個動態成分裁判使用終極版,反應並且反應路由器-DOM 4.x的

class MatchBox extends React.Component { 
    constructor(props) { 
     super(props); 

     this.countdownHandler = null; 
     this.showBlocker = true; 

     this.start = this.start.bind(this); 
    } 

    start() { 
     ... 
    } 

    render() { 
     ... 

     return (
      <div style={ styles.mainContainer } className="fluid-container"> 
       ... 
      </div> 
     ); 
    } 
}; 

function mapStateToProps(state) { 
    ... 
} 

function matchDispatchToProps(dispatch) { 
    ... 
} 

export default withRouter(connect(mapStateToProps, matchDispatchToProps, null, { withRef: true })(MatchBox)); 

其在此類使用

class GameBox extends React.Component { 
    constructor(props) { 
     super(props); 

     ... 
    } 

    render() { 
     var mainElement = null; 
     switch(this.props.mainElement.element) { 
      case 'SEARCHING': mainElement = <SearchingBox gameType={ this.props.gameType }/>; break; 
      case 'MATCH': mainElement = <MatchBox ref='matchBox'/>; break; 

      default: mainElement = <SearchingBox/>; 
     } 

     return (
      <div style={ styles.mainContainer } className="fluid-container"> 
       { mainElement } 
      </div> 
     ); 
    } 
}; 

function mapStateToProps(state) { 
    ... 
} 

function matchDispatchToProps(dispatch) { 
    ... 
} 

export default withRouter(connect(mapStateToProps, matchDispatchToProps, null, { withRef: true })(GameBox)); 

而我無法獲得對象MatchBox的引用。我嘗試this.refs.matchBox並且爲空,也試圖直接從ref(ref={(r) => { // r is null } }),我不知道該怎麼嘗試了。 我正在使用react-router-dom 4,我不知道函數withRouter是否影響結果組件。

回答

1

這並不美觀,但我認爲這是解決方案。 withRouter通過wrappedComponentRef回調暴露了子ref,這使我們可以訪問connect hoc。如果您像通過withRef屬性那樣通過getWrappedInstance公開其子女人員參考。所以你只需要將這兩者結合起來。

class GameBox extends React.Component {  
    matchboxRefCallback = (connectHOC) => { 
     this.matchboxRef = connectHOC ? connectHOC.getWrappedInstance() : null; 
    } 
    render() { 
     return <MatchBox wrappedComponentRef={this.matchboxRefCallback}/>; 
    } 
} 
+0

這是上帝的救恩 –