簡體   English   中英

使用Redux,React和react-router-dom 4.x時從動態組件獲取引用

[英]Getting the ref from a dynamic component when using Redux, React and react-router-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並為null,也嘗試直接從ref( ref={(r) => { // r is null } } )獲取,但我不知道該怎么做。 我正在使用react-router-dom 4,我不知道withRouter函數withRouter會影響結果組件。

這不是很漂亮,但是我認為這是解決方案。 withRouter通過wrappedComponentRef回調公開子引用,這使我們進入了connect hoc。 如果您像以前那樣傳遞withRef屬性,則會通過getWrappedInstance公開其子引用。 因此,您只需將兩者結合起來即可。

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

更清潔的解決方案是創建HOC。 它將引用轉發到實際組件

const matchBoxHOC = (WrappedComponent) => {

    class MatchBoxHOC extends React.Component {
        render() {
            const { forwardRef, ...rest } = this.props;
            return <WrappedComponent {...rest} ref={forwardRef} />;
        }
    }

    const WithRouterMatchBoxHOC = withRouter(MatchBoxHOC, { withRef: true });

    return React.forwardRef((props, ref) => {
        return <WithRouterMatchBoxHOC {...props} forwardRef={ref} />;
    });
}

通話就像

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM