我有一个带有max-height和overflow-y: auto的ul。
当用户输入足够多的li元素时,ul开始滚动,但我希望包含form的最后一个li始终呈现给用户并可见。
我尝试实现了一个如下所示的scrollToBottom函数:
scrollToBottom() {
this.formLi.scrollIntoView({ behavior: 'smooth' });
}但这只会使ul跳到屏幕顶部,并将其中包含表单的li显示为唯一可见的内容。
有没有更好的方法来实现这一点?我发现的答案往往有点旧,使用的是ReactDOM。谢谢!
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>发布于 2020-04-17 15:23:37
我有一个可以填满整个页面高度的容器。此容器有显示flex和flex方向列。然后我有一个Messages组件,它是一个ul,每条消息有一个li,另外还有一个特殊的AlwaysScrollToBottom组件作为最后一个子组件,在useEffect的帮助下滚动到列表的底部。
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被省略了,它包含表单、输入字段等来发送消息。
发布于 2017-08-24 19:36:35
使用react-scroll库。但是,您必须显式设置ul的ID。
import { animateScroll } from "react-scroll";
scrollToBottom() {
animateScroll.scrollToBottom({
containerId: "options-holder"
});
}您可以在setState回调中调用scrollToBottom。
例如
this.setState({ items: newItems}, this.scrollToBottom);或者使用setTimeout。
或者,您甚至可以从react-scroll设置Element并滚动到某个li。
发布于 2017-08-25 07:05:08
当涉及到呈现来自用户导入的组件数组时,我遇到了类似的问题。我最终使用了componentDidUpdate()函数来让我的函数正常工作。
componentDidUpdate() {
// I was not using an li but may work to keep your div scrolled to the bottom as li's are getting pushed to the div
const objDiv = document.getElementById('div');
objDiv.scrollTop = objDiv.scrollHeight;
}https://stackoverflow.com/questions/45719909
复制相似问题