使用webpack2中的System异步的组件,定义ref不生效

图片描述

类似这种方式,动态再render中设定ref是可以获取的,但是让lazilyLoad一封装ref就不生效了,可是其他的props是有的,不明白发生了什么..

没有用过这个组件的可以看下面LazilyLoad的组件.


import React from 'react';

/**
 * @function 支持异步加载的封装组件
 */
class LazilyLoad extends React.Component {

    constructor() {
        super(...arguments);
        this.state = {
            isLoaded: false,
        };
    }

    componentWillMount() {
        this.load(this.props);
    }

    componentDidMount() {
        this._isMounted = true;
    }

    componentWillReceiveProps(next) {
        if (next.modules === this.props.modules) return null;
        this.load(next);
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

    load(props) {
        this.setState({
            isLoaded: false,
        });

        const {modules} = props;
        const keys = Object.keys(modules);

        Promise.all(keys.map((key) => modules[key]()))
            .then((values) => (keys.reduce((agg, key, index) => {
                agg[key] = values[index];
                return agg;
            }, {})))
            .then((result) => {
                if (!this._isMounted) return null;
                this.setState({modules: result, isLoaded: true});
            });
    }

    render() {
        if (!this.state.isLoaded) return null;
        console.log(this.props);
        // console.log(this.state.modules);
        return React.Children.only(this.props.children(this.state.modules));
    }
}

LazilyLoad.propTypes = {
    children: React.PropTypes.func.isRequired,
};

export const LazilyLoadFactory = (Component, modules) => {
    return (props) => (
    <LazilyLoad modules={modules}>
        {(mods) => <Component {...mods} {...props} />}
    </LazilyLoad>
    );
};

export const importLazy = (promise) => (
    promise.then((result) => result.default)
);

export default LazilyLoad;
阅读 2.9k
2 个回答

你的这种情况因为被第三方的插件包裹了,所以你回去的ref是第三方的,并不是你所想要的,所以这个方法不可取。
你的这个类似于redux中connect你的组件,类似于下面的这个

const mapStateToProps= (state)=>{
  const {hrSetting:{organizations,employeesLookup}}= state;
  return {
      organizations,
      employeesLookup
  };
}

export default connect(mapStateToProps)(ListOfTable);

此时你的组件就被Connect包裹了,所以你获取不到你想要的ref了

图片描述

ref='asd'这种写法官方不建议使用了,你可以试试ref={r => this.asd = r}能不能得到正确的引用?其他代码看了一下好像没什么问题。实在不行,可以包装一层试下,比如:

({LoadedLate}) => {
    return <div ref={r => this.asd = r}><LoadedLate uuid={SliderId} /></div>
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题