滚动到React中溢出的div的底部 [英] Scroll to bottom of an overflowing div in React
问题描述
我有一个 ul
,其中 max-height
和 overflow-y:auto
.
当用户输入足够的 li
元素时, ul
开始滚动,但是我希望最后一个 li
具有 form
始终显示给用户并对其可见.
When the user enters enough li
elements, the ul
starts to scroll, but I want the last li
with the form
in it to always be present and viewable to the user.
我已经尝试实现如下所示的 scrollToBottom
函数:
I've tried implementing a scrollToBottom
function that looks like this:
scrollToBottom() {
this.formLi.scrollIntoView({ behavior: 'smooth' });
}
但这只是使 ul
跳到屏幕顶部,并显示其中带有表单的 li
是唯一可见的内容.
But that just makes the ul
jump to the top of the screen and show the li
with the form in it as the only visible thing.
是否有更好的方法来做到这一点?我发现的答案往往有些老,并且使用ReactDOM.谢谢!
Is there a better way to accomplish this? Answers I find tend to be a bit older and use ReactDOM. Thanks!
CSS:
.prompt-box .options-holder {
list-style: none;
padding: 0;
width: 95%;
margin: 12px auto;
max-height: 600px;
overflow-y: auto;
}
HTML:
<ul className='options-holder'>
{
this.state.items.map((item, index) => (
<li key={item.id} className={`option ${index === 0 ? 'first' : ''}`}>
<div className='circle' onClick={this.removeItem} />
<p className='item-text'>{ item.text }</p>
</li>
))
}
<li key={0} className={`option form ${this.state.items.length === 0 ? 'only' : ''}`} ref={el => (this.formLi = el)}>
<div className='circle form' />
<form className='new-item-form' onSubmit={this.handleSubmit}>
<input
autoFocus
className='new-item-input'
placeholder='Type something and press return...'
onChange={this.handleChange}
value={this.state.text}
ref={(input) => (this.formInput = input)} />
</form>
</li>
</ul>
推荐答案
我有一个填充页面高度的容器.此容器具有display flex和flex direction列.然后,我有一个 Messages
组件,它是一个 ul
组件,每条消息一个 li
组件,另外还有一个特殊的 AlwaysScrollToBottom
组件作为最后一个在 useEffect
的帮助下滚动到列表底部的孩子.
I have a container that fills the height of the page. This container has display flex and flex direction column. Then I have a Messages
component which is a ul
with one li
per message plus a special AlwaysScrollToBottom
component as the last child that, with the help of useEffect
, scrolls to the bottom of the list.
const AlwaysScrollToBottom = () => {
const elementRef = useRef();
useEffect(() => elementRef.current.scrollIntoView());
return <div ref={elementRef} />;
};
const Messages = ({ items }) => (
<ul>
{items.map(({id, text}) => <li key={id}>{text}</li>)}
<AlwaysScrollToBottom />
</ul>
)
const App = () => (
<div className="container">
<Messages items={[...]}>
<MessageComposer />
</div>
)
CSS是
.container {
display: flex;
height: 100vh;
flex-direction: column;
}
ul {
flex-grow: 1;
overflow-y: auto;
}
为简洁起见,已省略了
MessageComposer
,它包含用于发送消息的表单,输入字段等.
MessageComposer
has been omitted for brevity, it contains the form, the input field, etc. to send messages.
这篇关于滚动到React中溢出的div的底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!