2017-06-21 112 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

这是上帝的救恩 –