繁体   English   中英

scrollIntoView使用React引用

[英]scrollIntoView using React refs

我们正在尝试在用户关闭另一个组件时滚动到特定组件。

我们的示例与下面的示例非常类似,取自https://reactjs.org/docs/refs-and-the-dom.html#exposing-dom-refs-to-parent-components

function CustomComponents(props) {
  const items = [1,2,3,4].map((x, i) => return (
    <div ref={props.inputRef} key={i}>
     x + hello
    </div>
  )

  return (
    <div>
      { items }
    </div>
  );
}

function Parent(props) {
  return (
    <div>
      <CustomComponents inputRef={props.inputRef} />
    </div>
  );
}


class Grandparent extends React.Component {
  render() {
    return (
      <Parent
        inputRef={el => this.inputElement = el}
      />
    );
  }
}

我们正在渲染this.refs[elem].scrollIntoView()卡片,希望能够通过调用this.refs[elem].scrollIntoView()滚动到特定的卡片。

但我们的问题是调用this.refs在所有级别返回一个空对象,因此我们无法附加到特定元素,然后在用户返回查看此组件时触发它。

想要一些人如何解决这个问题。

你想在哪里调用this.refs[elem].scrollIntoView() 您应该在componentDidMountcomponentDidUpdate使用ref ,而不是在render方法中。

我通过在祖父母组件中提供下面写的if语句解决了我的具体问题。

inputRef={el => { 
  if (el && el.id == this.state.selectedBuildingRef) {
    this.myelement.scrollIntoView();
    window.scrollBy(0, -65);
  } 
}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM