react.js - react中设置window.resize时,ref获取元素失败,如何解决?

查看:219
本文介绍了react.js - react中设置window.resize时,ref获取元素失败,如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

...
class Main extends React.Component {
    constructor(props){
        super(props) 
    }
    componentDidMount(){
        window.addEventListener('resize', this.resizeListener);
        this.resizeListener();
    }
    componentWillUnmount() {
        window.removeEventListener('resize', this.resizeListener);
    }
    resizeListener() {
        console.log(this.rootRef)//**这里当改变窗口大小时,打印的是undefined**
        
        const node = this.rootRef
        
        const temp = document.createElement('div');
        temp.setAttribute('class', 'cell');
        document.body.appendChild(temp);

        const cellWidth = temp.offsetWidth,
        cellMargin = 8,
        componentWidth = cellWidth + 2 * cellMargin,
        maxn = Math.floor(document.body.offsetWidth / componentWidth);
        console.log(`componentWidth=${componentWidth}`)
        console.log(`document.body.offsetWidth=${document.body.offsetWidth}`)
        try {
            console.log(`maxn=${maxn * componentWidth}`)
            node.style.width = String(`${maxn * componentWidth}px`);
        } catch (e) {}

        document.body.removeChild(temp);
    }
    render(){
        return (
            <div className={this.props.classes.root}>
                <AppBar position="static" color="accent">
                        <Toolbar>
                            <IconButton color="contrast" aria-label="Menu">
                                <MenuIcon />
                            </IconButton>
                            <Typography type="title" color="inherit" className={this.props.classes.flex}>
                                测试
                            </Typography>
                            <Button color="contrast">登录</Button>
                        </Toolbar>
                </AppBar>
                <div ref={ref => (this.rootRef = ref)} className={this.props.classes.container}>
                    <Grid container spacing={0} align="center" justify="center">
                        <Grid item xs >
                            <ImageGridList/>
                        </Grid>
                    </Grid>
                </div>
            </div>
        );
    }
}
...

解决方案

window.removeEventListener('resize', ::this.resizeListener);

或者

resizeListener = ()=>{ .... }

这篇关于react.js - react中设置window.resize时,ref获取元素失败,如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆