栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何滚动div在ReactJS中可见?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何滚动div在ReactJS中可见?

我假设您具有某种

List
组件和某种
Item
组件。我在一个项目中执行此操作的方式是让该项目知道它是否处于活动状态。该项目将要求列表在必要时将其滚动到视图中。考虑以下伪代码:

class List extends React.Component {  render() {    return <div>{this.props.items.map(this.renderItem)}</div>;  }  renderItem(item) {    return <Item key={item.id} item={item}      active={item.id === this.props.activeId}      scrollIntoView={this.scrollElementIntoViewIfNeeded} />  }  scrollElementIntoViewIfNeeded(domNode) {    var containerDomNode = React.findDOMNode(this);    // Determine if `domNode` fully fits inside `containerDomNode`.    // If not, set the container's scrollTop appropriately.  }}class Item extends React.Component {  render() {    return <div>something...</div>;  }  componentDidMount() {    this.ensureVisible();  }  componentDidUpdate() {    this.ensureVisible();  }  ensureVisible() {    if (this.props.active) {      this.props.scrollIntoView(React.findDOMNode(this));    }  }}

更好的解决方案可能是使列表负责将项目滚动到视图中(而无需使项目知道它甚至在列表中)。为此,您可以将

ref
属性添加到特定项目并使用以下内容找到它:

class List extends React.Component {  render() {    return <div>{this.props.items.map(this.renderItem)}</div>;  }  renderItem(item) {    var active = item.id === this.props.activeId;    var props = {      key: item.id,      item: item,      active: active    };    if (active) {      props.ref = "activeItem";    }    return <Item {...props} />  }  componentDidUpdate(prevProps) {    // only scroll into view if the active item changed last render    if (this.props.activeId !== prevProps.activeId) {      this.ensureActiveItemVisible();    }  }  ensureActiveItemVisible() {    var itemComponent = this.refs.activeItem;    if (itemComponent) {      var domNode = React.findDOMNode(itemComponent);      this.scrollElementIntoViewIfNeeded(domNode);    }  }  scrollElementIntoViewIfNeeded(domNode) {    var containerDomNode = React.findDOMNode(this);    // Determine if `domNode` fully fits inside `containerDomNode`.    // If not, set the container's scrollTop appropriately.  }}

如果您不希望做数学运算来确定该项是否在列表节点内可见,则可以使用DOM方法

scrollIntoView()
或特定于Webkit的Webkit
scrollIntoViewIfNeeded
,它可以使用polyfill,因此可以在非Webkit浏览器中使用它。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/568403.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号