当在react js中动态添加到正文中的数据时滚动到页面底部?

IT技术 reactjs
2021-05-05 01:41:13

我有一个像下面这样的组件:

class App extends React.Component {
    constructor(props){
        super(props);
    }
    render() { 
        return (
            <div>
                {this.state.renderedThings.map((element, index) => (
                    <div key={index} className="cont">
                        <img alt="avatar" className="BlockOneImg" src={`./${element.image}.png`} role="presentation"/>
                    </div>
                )}
            </div>
        )
    }
}

每次都会动态添加图像,我需要滚动到添加的当前图像。

1个回答

我已完成以下操作以滚动到底部或最近添加的 DOM:

在您的图像 div 中添加 ref ,如下所示:

<div key={index} className="cont" ref={(ref) => this.newData = ref}        
   <img alt="avatar" className="BlockOneImg" src={`./${element.image}.png`}/>
</div>

并添加如下的生命周期:

componentDidUpdate() {
    this.newData.scrollIntoView({ behavior: "smooth" })
}

希望这有效!