我想在访问页面(渲染组件)或更新页面后,自动滚动到页面(组件)的底部。我尝试过refs和react-scroll库,但没有成功。下面是我的代码:
使用refs:
class CommentsDrawer extends Component {
componentDidMount() {
this.scrollToBottom();
}
componentDidUpdate() {
this.scrollToBottom();
}
scrollToBottom = () => {
this.messagesEnd.scrollIntoView({ behavior: "smooth" });
};
render() {
const { show, closeDrawer } = this.props;
let drawerClasses = styles.drawer;
if (show) {
drawerClasses = `${styles.drawer} ${styles.open}`;
}
return (
<div className={drawerClasses}>
<div>
<CommentsDrawerHeader closeDrawer={closeDrawer} numOfComments={mockedData.length} />
</div>
<CommentsList data={mockedData} />
{/* TODO: Reply functionality is just a mockup for this task scope. To be fully implemented in the integration task. */}
<CommentInput />
<div ref={(el) => { this.messagesEnd = el; }} />
</div>
);
}
}
发布于 2020-10-04 20:42:01
解决方案是在组件的构造函数中创建引用。我已经在呈现注释的子组件中进行了实现。
mport React, { Component, createRef } from "react";
import { array, func, boolean } from "prop-types";
import Comment from "../Comment/Comment";
import styles from "./CommentsList.scss";
class CommentsList extends Component {
static propTypes = {
// eslint-disable-next-line react/forbid-prop-types
data: array.isRequired,
sendReply: func,
deleteReply: func,
show: boolean
};
static defaultProps = {
sendReply: () => {},
deleteReply: () => {},
show: true
};
constructor(props) {
super(props);
this.bottomRef = createRef();
}
componentDidMount() {
this.scrollToBottom();
}
shouldComponentUpdate() {
if (!this.props.show) {
this.scrollToBottom();
}
}
scrollToBottom = () => {
this.bottomRef.current.scrollIntoView({ behavior: "smooth" });
};
render() {
const { data, sendReply, deleteReply } = this.props;
return (
<div className={styles.comments__list}>
{data.map(el => (
<Comment
// eslint-disable-next-line no-underscore-dangle
key={el._id}
// eslint-disable-next-line no-underscore-dangle
id={el._id}
by={el.by}
jobTitle={el.jobTitle}
timestamp={el.at}
comment={el.comment}
// eslint-disable-next-line no-undef
replyTo={!_.isUndefined(el.replyTo) && el.replyTo}
origin={el.origin}
sendReply={sendReply}
deleteReply={deleteReply}
/>
))}
<div ref={this.bottomRef} />
</div>
);
}
}
export default CommentsList;
https://stackoverflow.com/questions/64192530
复制相似问题