我有一个带有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-03-19 20:36:59
我用一个通用的实用函数解决了这个问题,这个函数可以在任何特定组件之外工作。您需要在父元素(列表框、多行编辑等)和最后一个子元素(或您希望滚动到的任何位置)上定义ref。
export const scrollToRef = (parentRef, childRef) => {
trace("scrollToRef:ref.current.offsetTop", childRef.current.offsetTop);
parentRef.current.scrollTo(0, childRef.current.offsetTop)
}我使用它作为一个功能组件,并在父容器更新时调用它作为效果。
https://stackoverflow.com/questions/45719909
复制相似问题